content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def to_camel_case(string: str) -> str:
"""
Converts a ``snake_case`` string to ``camelCase``.
:param string: A ``snake_case`` string.
:return: A ``camelCase`` version of the input.
"""
components = string.split("_")
return components[0] + "".join(x.capitalize() for x in components[1:]) | 44,100 |
def reconnect(user_data):
"""
Attempt to perform a login to the Unistudium website, saving the cookies in user_data.
Returns:
"OK" if the login was performed correctly, else a description with the error that can be used to inform the users.
"""
# Check if user's session exists
if 'sessi... | 44,101 |
def p_testlist_multi(p):
"""testlist_multi : testlist_multi COMMA test
| test"""
if len(p) == 2:
# singleton
p[0] = p[1]
else:
if isinstance(p[1], list):
p[0] = p[1] + [p[3]]
else:
# singleton -> tuple
p[0] = [p[1], p[... | 44,102 |
def flatten(encoded_tree: dict, clopen_state: dict) -> None:
"""
Transform and enriches an encoded tree into the format expected by the frontend library.
:param encoded_tree: A tree as returned by the transcode function
:param clopen_state: A dictionary that keeps track of the open-closed state of a no... | 44,103 |
def test_mutate_non_staff(rf, user_factory):
"""
If the requesting user is not a staff user, an exception should be
raised.
"""
mutation = schema.CreateTeam()
user = user_factory()
request = rf.post("/")
request.user = user
with pytest.raises(Exception):
mutation.mutate(Dum... | 44,104 |
def yake(
doc: Doc,
*,
normalize: Optional[str] = "lemma",
ngrams: int | Collection[int] = (1, 2, 3),
include_pos: Optional[str | Collection[str]] = ("NOUN", "PROPN", "ADJ"),
window_size: int = 2,
topn: int | float = 10,
) -> List[Tuple[str, float]]:
"""
Extract key terms from a docu... | 44,105 |
def make_interval_plot(d, ax, start, end, show_temps = True, show_sun = True, c = 'blue'):
"""
Given a building record, an axis, and a start/end, plot the interval between the start and end.
Parameters:
d -- The building record.
ax -- The axis.
start -- Index of start time.
end -- Index of ... | 44,106 |
def test_get_virtual_roots(xsession: XSession):
"""Tests that the list of virtual can be retrieved."""
virtual_roots = xsession.get_virtual_roots()
if virtual_roots is not None:
assert isinstance(virtual_roots, list) | 44,107 |
def parse_qsub_defaults(parsed):
"""Unpack QSUB_DEFAULTS."""
d = parsed.split() if type(parsed) == str else parsed
options={}
for arg in d:
if "=" in arg:
k,v = arg.split("=")
options[k.strip("-")] = v.strip()
else:
options[arg.strip("-")] = ""
... | 44,108 |
def load_embeddings(word_map=None, binary=True):
"""
Creates an embedding tensor for the specified word map, for loading into the model.
:param word_emb_file: file containing embeddings (stored in GloVe format)
:param word_map: word map. If None, it will be comprised from the embeddings vocabulary
:... | 44,109 |
def update_business_profile(business: Business, profile_info: Dict) -> Dict:
"""Set the legal type of the business."""
if not business or not profile_info:
return {'error': babel('Business and profile_info required.')}
# contact phone is optional
phone = profile_info.get('phone', '')
error... | 44,110 |
def nextpow2(i):
""" Find the next power of 2 for number i """
n = 1
while n < i:
n *= 2
return n | 44,111 |
def _extra_topo_sort(bad_ordering: Sequence[DiscoveredExtension]) -> Sequence[DiscoveredExtension]:
"""
Simple depth-first search version of a topological sort, but without
recursion.
:param bad_ordering:
:return:
"""
lookup: Dict[str, DiscoveredExtension] = {}
for node in bad_ordering... | 44,112 |
def getclasesbyid_(numid):
"""
Returns all defined clases by id [number]
"""
data = get_info_token()
user_ = data['User']
rol_ = data['Rol']
data_response = ''
if rol_ == 'Professor':
try:
bool_, data_response = getclassbyid_(data['User'],numid)
if bool_:
... | 44,113 |
def load_versions():
"""Load Bioversions data."""
with open(VERSIONS_PATH) as file:
return json.load(file) | 44,114 |
async def retrieve_document(document_id: str, collection: str) -> dict:
"""
:param document_id:
:param collection:
:return:
"""
document_filter = {"_id": ObjectId(document_id)}
if document := await greens.app.state.mongo_collection[collection].find_one(document_filter):
return await... | 44,115 |
def get_kalliope_poststukken_uit(path, session, from_,
to=None,
dossier_types=None):
"""
Perform the API-call to get all poststukken-uit that are ready to be processed.
:param path: url of the api endpoint that we want to fetch
:param se... | 44,116 |
def export_image(filename=None, type='PNG', resolution=None, units=None, height=None, width=None, zoom=None,
network=None, base_url=DEFAULT_BASE_URL):
""" Save the current network view as an image file.
The image is cropped per the current view in Cytoscape. Consider applying :meth:`fit_conten... | 44,117 |
def lstsq_cholesky(
coefs: np.ndarray,
result: np.ndarray,
) -> np.ndarray:
"""Solve OLS problem using a Cholesky decomposition."""
left = coefs.T @ coefs
right = coefs.T @ result
return scipy.linalg.solve(left, right, assume_a="pos") | 44,118 |
def get_packages(package):
"""Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, "__init__.py"))] | 44,119 |
def load_class_by_alias_or_classname(namespace, name):
"""Load a class using stevedore alias or the class name.
:param namespace: The namespace where the alias is defined.
:param name: The alias or class name of the class to be loaded.
:returns: Class if it can be loaded.
:raises ImportError: if cl... | 44,120 |
def _standardize(signals, demean=True, normalize=True, inplace=True,
verbose=False):
""" Center and norm a given signal (time is along first axis)
Attention: this will not center constant signals
but will replace these with colums of ones
Parameters
... | 44,121 |
def bbox_to_poly(bboxes: np.ndarray) -> np.ndarray:
"""
Expects bboxes in xyxy format. Turns each into a 1D array with 8 entries,
every consecutive pair being for one vertex (starting from top left and
going around clockwise)
Works with single bboxes (shape is (4, )) or multiple bboxes (shape is
... | 44,122 |
def test_projections_fits_example_in_wiki_RTK():
"""
Compare the two projections, in L2 norm
"""
assert norm(diff) <= tol * norm(projWiki)
assert norm(diff, 1) <= tol * norm(projWiki, 1)
assert norm(diff, 2) <= tol * norm(projWiki, 2)
assert norm(diff, np.inf) <= tol * norm(projWiki, np.... | 44,123 |
def waypts_2_pwsplines(wp_traj, dt, degree=1, plot=False):
"""
Convert a sequence of multi-dimensional sparse waypoints
to a sequence of interpolated multi-dimensional waypoints via splines.
Parameters
----------
wp_traj: horizon * n_s, a sequence of waypoints.
dt: duration of 1 time step o... | 44,124 |
def _bin_data(aa, bb, bins=10, verbose=False):
"""
If unbinned data has come in, do something smart
with it here.
Uses numpy.histogram for binning.
bins can be:
- int: number of bins
- list or array: bin boundaries, from min to max, half open on right,
like numpy, when bins=[1, 2, ... | 44,125 |
def initialize_logger(logger, logger_id, progress_bar=None, log_queue=None):
"""
Initialize logger for the :class:`pyro.infer.mcmc` module.
:param logger: logger instance.
:param str logger_id: identifier for the log record,
e.g. chain id in case of multiple samplers.
:param progress_bar: a... | 44,126 |
def test_meta_plus_classmethod(namespaceable, namespace):
"""Test using a classmethod in a Namespace, while messing with metaclasses.
This might have been purely for coverage of some kind? I forget.
"""
class Meta(namespaceable, type(namespaceable)):
"""A throwaway test metaclass."""
wi... | 44,127 |
def EncodeConstants(const_dict):
"""the NPU requires that weights are compressed and bias/scales are 'encoded', both
of which are performed by this pass.
This pass modifies both the constant dict to contain the post-encoding values of the
constants and the IR to adjust buffer types/sizes/accesses so th... | 44,128 |
def copyDirContents(source, destination, umask='000'):
""" Copy the contents of a folder recursively.
Could rewrite using shutil.copy / copytree?
"""
src = os.path.normpath(os.path.join(source, "*"))
dst = os.path.normpath(destination)
if platform.system() == "Windows":
cmdStr = 'copy /Y "%s" "%s"' %(src, dst... | 44,129 |
def naive_vis(x_train, y_train):
"""Create some plots of some simple summary statistics of the data
Args:
x_train: pandas DataFrame
Features for training
y_train: pandas Series
Targets for training
Returns:
None
"""
naive = get_naive_features(x_train... | 44,130 |
def count_tweet_shed_words_freq(tweet_text, ind_shed_word_dict, shed_word_ind_dict, shed_words_set):
"""
Count the frequency of selected Hedonometer words in tweet text.
param tweet_text: String of text field of tweet
return: dict of shed_word_ind to shed_word_freq mapping
"""
'''... | 44,131 |
def test_against_David_Law():
""" Test my code against an output file from using David Law's cpp code. Do:
g++ SgrCoord.cpp; ./a.out
to generate the data file, SgrCoord_data.
"""
filename = get_pkg_data_filename('SgrCoord_data')
law_data = np.genfromtxt(filename, names=True, delim... | 44,132 |
def parse_date(text):
"""Return POSIX timestamp obtained from parsing date and time from given
date string.
Return None if no text given.
"""
if text:
return dateparser.parse(text).timestamp() | 44,133 |
def format(table, field, fmt, **kwargs):
"""
Convenience function to format all values in the given `field` using the
`fmt` format string.
The ``where`` keyword argument can be given with a callable or expression
which is evaluated on each row and which should return True if the
conversion shou... | 44,134 |
def colorbias(img, refcolor=np.array([1.,0,0])):
""" Compute Color Bias """
img_hsv = skimage.color.rgb2hsv(img)
refcolor = skimage.color.rgb2hsv(refcolor.reshape(1,1,3)) # to make it compatible
#dH = np.abs(np.sin((img_hsv[...,0] - refcolor[...,0])))
#dS = np.abs(img_hsv[...,1] - refcolor[...,1])
... | 44,135 |
def walk_json(e, dict_fct=i, list_fct=i, num_fct=i, str_fct=i, bool_fct=i, null_fct=i, not_found=not_found_default):
"""
Go throught a json and call each function accordingly of the element type
for each element, the value returned is used for the json output
This doesn't change the input json, but re-c... | 44,136 |
def replaceFile(oldname, newname):
""" Rename file 'oldname' to 'newname'.
"""
if os.name == 'nt' and os.path.exists(oldname):
# POSIX rename does an atomic replace, WIN32 rename does not. :-(
try:
os.remove(newname)
except OSError, exc:
import errno
... | 44,137 |
def colIm(z):
"""Returns a colour where log(Im(z)) is represented by hue.
This makes it easy to see where Im(z) converges to 0"""
h = np.log(z.imag)*pi
l = np.clip(0.5+0.05*z.real,0.1,0.9)
s = 1
c = hsl2rgb(h,s,l)
return c | 44,138 |
def gsl_blas_zdotc(*args, **kwargs):
"""gsl_blas_zdotc(gsl_vector_complex const * X, gsl_vector_complex const * Y, gsl_complex * dotc) -> int"""
return _gslwrap.gsl_blas_zdotc(*args, **kwargs) | 44,139 |
def random_neighbour(vec,myid,n):
"""Generates a random binary vector that is 1-bit away (a unit Hamming distance)
Args:
vec (list or numpy.ndarray): An input vector
myid (int): An id of an agent of interest
n (int): Number of tasks allocated to a single agent
Returns:
list... | 44,140 |
def reset(config_file):
"""Restores the configuration file to its original state."""
if config_file.path == STB_INTERNAL_CONFIG_FILE:
click.secho(
"You're using the internal configuration file, can't reset.", fg="red"
)
else:
config_file.restore_original(original_path=STB... | 44,141 |
def _degree_of_endstopping(model, block, image, weight_id0, weight_id1, weight_id2):
"""Passes image to model and records the activations of block. The
activations are normalized to be in [0, 1] and then summed over using
different weighted masks.
Parameters
----------
model : nn.Module
... | 44,142 |
def posts(parsed):
"""Calculates number of every type of post"""
num_t_post = 0
num_corner_post = 0
num_line_post = 0
num_end_post = 0
num_gate_posts = 0
for post in parsed.posts():
if not post.isRemoval:
if post.postType == 'tPost':
num_t_post += 1
... | 44,143 |
def _compute_populations(mvts: pd.DataFrame, label_col_name) -> dict:
"""
A private method that computes the population corresponding to each class label.
:param mvts: The dataframe who class population is of interest.
:param label_col_name: The column-name corresponding to the class labels in `mvts`.
... | 44,144 |
def plot_avg_sum_capacity_comparison(
df: pd.DataFrame, port1: str, port2: str, vessel_type: str
) -> go.Figure:
"""
Returns a figure for the first chart on the Compare tab. It shows per day comparison between
average sum of capacity by applied conditions.
:param df: Pandas DataFrame, input data
... | 44,145 |
def fetchUrlPages(url: str, cacheDir: str = None) -> dict:
"""
Realiza a requisição dos dados da API retornando os dados paginados.
https://openbanking-brasil.github.io/areadesenvolvedor-fase1/#introducao-paginacao
"""
root = fetchUrl(url, cacheDir = cacheDir)
if root == None or not type(root) ... | 44,146 |
def _add_cloud_distro_check(cloud_archive_release, openstack_release):
"""Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the corr... | 44,147 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up the rinnaitouch integration from a config entry."""
ip_address = entry.data.get(CONF_HOST)
_LOGGER.debug("Get controller with IP: %s", ip_address)
try:
system = RinnaiSystem.get_instance(ip_address)
#scenes... | 44,148 |
def num_neighbours(lag=1):
"""
Calculate number of neigbour pixels for a given lag.
Parameters
----------
lag : int
Lag distance, defaults to 1.
Returns
-------
int
Number of neighbours
"""
win_size = 2*lag + 1
neighbours = win_size**2 - (2*(lag-... | 44,149 |
def get_solr_data_recommend(function, reader, rows=5, sort='entry_date', cutoff_days=5, top_n_reads=10):
"""
:param reader:
:param rows:
:param sort:
:param cutoff_days:
:param top_n_reads:
:return:
"""
query = '({function}(topn({topn}, reader:{reader}, {sort} desc)) entdate:[NOW-{c... | 44,150 |
def normalize_key(key):
"""
Formata a chave para ser utilizada no json.
Args:
key (string): Campo coletado no scraping dos dados do MEC.
Returns:
Retorna a sttring formatada para ser utilizada no json.
"""
aux = key.strip(' :').replace(' ', '_').lower()
... | 44,151 |
def line(p0=(0,0), p1=(1,0)):
"""
p0 p1
o-----------o
+--> u
"""
p0 = np.asarray(p0, dtype='d')
p1 = np.asarray(p1, dtype='d')
points = np.zeros((2,3), dtype='d')
points[0,:p0.size] = p0
points[1,:p1.size] = p1
knots = [0,0,1,1]
return NURBS([knots], points) | 44,152 |
def test_matcher_uses_on_match_callback(matcher: RegexMatcher, doc: Doc) -> None:
"""It utilizes callback on match functions passed when called on a Doc object."""
matcher(doc)
assert "usa" in [ent.text for ent in doc.ents] | 44,153 |
def superior():
"""a fixture for lake superior"""
superior = LakeFactory(lake_name="Lake Superior", abbrev="SU")
return superior | 44,154 |
def hsv_mask(img, hue_mask, sat_mask, val_mask):
"""
Returns a binary image based on the mask thresholds
:param img: The image to mask
:param hue_mask: Tuple of (hue_min, hue_max)
:param sat_mask: Tuple of (sat_min, sat_max)
:param val_mask: Tuple of (val_min, val_max)
:return: Binary image ... | 44,155 |
def convert_parameter_dict_to_presamples(parameters):
"""Convert a dictionary of named parameters to the form needed for ``parameter_presamples``.
``parameters`` should be a dictionary with names (as strings) as keys and Numpy arrays as values. All Numpy arrays should have the same shape.
Returns (numpy s... | 44,156 |
def convert_to_rle(annotation, width, height):
"""Convert complex polygons to COCO RLE format.
Arguments:
annotation: a dictionary for an individual annotation in Darwin's format
Returns: an annotation in encrypted RLE format and a bounding box
@author Dinis Gokaydin <d.gokaydin@nationaldrones.... | 44,157 |
def test_suggest_delete_local_ixf_no_flag(entities, capsys):
"""
Automatic updates for network are disabled.
There is no remote-ixf corresponding to an existing netixlan.
There is a local-ixf corresponding to that netixlan but it does not flag it
for deletion.
We flag the local-ixf for deletion,... | 44,158 |
def getfqdn(name=None):
"""return (a) local IPv4 or v6 FQDN (Fully Qualified Domain Name)
if name is not given, returns local hostname
may raise socket.gaierror"""
return _getfqdn(socket.AF_UNSPEC, name) | 44,159 |
def create_answer_dict(elem, restrict_elem=None, checkbox=False):
"""
Construct dict with choices to fulfil form's div attribute
:param elem: ElemntTree element
:param restrict_elem: name of element which is not included in choice text
:param checkbox: boolean flag to work return data for checkbox ... | 44,160 |
def fasta(file_allname: str):
"""
需要传入file_allname的路径
:param file_allname:
:return: 返回fasta格式的序列list
"""
try:
# file_allname = input("输入你要分析出的文件,包括后缀名\n")
f = open(file_allname).read()
fasts = f.split(">")
fast_seq = []
index = 0
for fa... | 44,161 |
def ensure_variables_initialized(variables=None, name=None):
"""
Ensure variables are initialized.
Args:
variables (list[tf.Variable] or dict[str, tf.Variable]): Ensure only
the variables within this collection to be initialized. If not
specified, will ensure all variables w... | 44,162 |
def ask_version(version):
""" interact with user to determine what to do"""
upgrades = get_upgrades()
latest = get_latest(version, upgrades)
answer = False
if latest > version:
msg = "a new version (%s) is available. You have %s. Upgrade?" % (latest, version)
answer = True if raw_inp... | 44,163 |
def format_size(size):
"""
:param float size:
:rtype: str
"""
size = float(size)
unit = 'TB'
for current_unit in ['bytes', 'KB', 'MB', 'GB']:
if size < 1024:
unit = current_unit
break
size /= 1024
return '{0:.2f}'.format(size).rstrip('0').rstrip('... | 44,164 |
def make_full_block_header_list(block_header):
"""Order all block header fields into a list."""
return make_short_block_header_list(block_header) + [
block_header.timestamp,
block_header.extraData,
] | 44,165 |
def path_constructor(
loader: Union[Loader, FullLoader, UnsafeLoader], node: Node
) -> PathLike:
"""
Extract the matched value, expand env variable, and replace the match.
:param loader: not used
:param node: YAML node
:return: path
:raises SyntaxError: if the node value does not match the ... | 44,166 |
def rc_seq(seq=""):
"""Returns the reverse compliment sequence."""
rc_nt_ls = []
rc_dict = {
"a": "t",
"c": "g",
"t": "a",
"g": "c",
"n": "n",
"A": "T",
"C": "G",
"T": "A",
"G": "C",
"N": "N"
}
rc_nt_ls = [rc_dict[seq[i]... | 44,167 |
def deduplicate(directories: List[str], recursive: bool,
dummy_run: bool) -> None:
"""
De-duplicate files within one or more directories. Remove files
that are identical to ones already considered.
Args:
directories: list of directories to process
recursive: process subd... | 44,168 |
def descriptions(path, values):
"""Transform descriptions."""
if not values:
return
root = E.descriptions()
for value in values:
elem = E.description(
value['description'], descriptionType=value['descriptionType']
)
set_non_empty_attr(elem, '{xml}lang', value... | 44,169 |
def build_default_region_dataset(
metrics: Mapping[FieldName, Union[Sequence[float], TimeseriesLiteral]],
*,
region=DEFAULT_REGION,
start_date="2020-04-01",
static: Optional[Mapping[FieldName, Any]] = None,
) -> timeseries.MultiRegionDataset:
"""Returns a `MultiRegionDataset` containing metrics ... | 44,170 |
def process(entries):
"""
Look for Science Direct (SCOPUS) database to update the bibliography entries.
This update evaluates only '@ARTICLE' entry types.
:param entries: list of bibtex entries
:return:
"""
log.info("Seeking for Science Direct (SCOPUS) entries")
count = 0
for e in e... | 44,171 |
def load_espnet_model(model_path):
"""Load an end-to-end model from ESPnet.
:param model_path: Path to the model.
:type model_path: str
:return: The model itself, mapping from subword to index,
and training arguments used.
:rtype: (torch.nn.Module, dict, dict)
"""
model, train_... | 44,172 |
def full_match(nfa: NFA, text: Iterator[str]) -> Union[Match, None]:
"""
:param nfa: a NFA
:param text: a text to match against
:return: match or ``None``
"""
text_it = _peek(text, sof='', eof='')
curr_states_set = StatesSet()
next_states_set = StatesSet()
curr_states_set.extend(c... | 44,173 |
def smiles_tokenizer(line, atoms=None):
"""
Tokenizes SMILES string atom-wise using regular expressions. While this
method is fast, it may lead to some mistakes: Sn may be considered as Tin
or as Sulfur with Nitrogen in aromatic cycle. Because of this, you should
specify a set of two-letter atoms ex... | 44,174 |
def merge_parameter_sets(first: Set[ParameterDefinition], second: Set[ParameterDefinition]) -> Set[ParameterDefinition]:
"""
Given two sets of parameter definitions, coming from different dependencies for example, merge them into a single set
"""
result: Set[ParameterDefinition] = first.intersection(sec... | 44,175 |
def pca(data, submeans=0, keep=-1, flip=1, sparse=0):
"""Auto-selecting PCA, with data in columns.
The 'data' matrix should be ndims X npts.
If npts > ndims, then does a PCA directly.
If ndims > npts, then does PCA on transpose, and does appropriate normalization.
Returns (eigvals, eigvecs)...or som... | 44,176 |
def build_udp_header(src_port, dst_port, length):
"""Builds a valid UDP header and returns it
Parameters:
- src_port: A uint16 which will be used as source port for the UDP
header
- dst_port: A uint16 which will be used as destination port for the
UDP header
... | 44,177 |
def plot_confus_mat(y_true, y_pred, classes_on=None,
normalize='true',
linewidths=0.02, linecolor='grey',
figsize: tuple = (4, 3),
ax=None, fp=None,
**kwargs):
""" by default, normalized by row (true classes)
"""... | 44,178 |
def set_config_option(section: str, option: str, value: Any, write_to_disk: bool = False) -> bool:
"""
Function which updates configuration option value.
By default if "write_to_disk" is False, value will only be updated in memory and not on disk.
This means it won't be reflected in Plugin processes w... | 44,179 |
def test_extract_seq():
"""
AA
GT┘ <-bridge read
GACGGTTGC <-bridge contig
0123456789 <-contig coord
ctg_clv^ ^ice
...GACGGTTGC... <-genome
5678901234 <-genome coord
1 |
ref_clv^ ^ire
"""
ctg = MagicMock()
ctg.... | 44,180 |
def add_or_update_user(username):
"""
Gets twitter user and tweets from twitter DB
Gets user by "username" parameter.
"""
try:
# Gets back twitter user object
twitter_user = TWITTER.get_user(username)
# Either updates or adds user to our DB
db_user = (User.query.get(t... | 44,181 |
async def home():
"""
Home endpoint to redirect to docs.
"""
return RedirectResponse("/docs") | 44,182 |
def robust_hist(x, ax=None, **kwargs):
"""
Wrapper function to `plt.hist` dropping values that are not finite
Returns:
Axes
"""
mask = np.isfinite(x)
ax = ax or plt.gca()
ax.hist(x[mask], **kwargs)
return ax | 44,183 |
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = open(os.path.join(package, "__init__.py")).read()
return re.search(
r"^__version__ = ['\"]([^'\"]+)['\"]",
init_py,
re.MULTILINE,
).group(1) | 44,184 |
def base36encode(number, alphabet='0123456789abcdefghijklmnopqrstuvxxyz'):
"""Convert positive integer to a base36 string."""
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
# Special case for zero
if number == 0:
return alphabet[0]
base36 = ''
... | 44,185 |
def pipe(*args, **kwargs):
"""A source that builds a url.
Args:
item (dict): The entry to process
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe configuration. Must contain the key 'base'. May
contain the keys 'params' or 'path'... | 44,186 |
def get_rotation(rotation):
"""
Return the text angle as float. The returned
angle is between 0 and 360 deg.
*rotation* may be 'horizontal', 'vertical', or a numeric value in degrees.
"""
try:
angle = float(rotation)
except (ValueError, TypeError):
isString = isinstance(rota... | 44,187 |
def checkWrite(request):
"""Check write"""
try:
_path = request.query_params.get("path")
import os
_file = open(_path + "test.txt", "w")
_file.write("engine write test")
_file.close()
return HttpResponse(_path + "test.txt")
except ValueError as e:
ret... | 44,188 |
def prob_random():
"""Prints out the states of various RNGs."""
print('random state: python %.3f torch %.3f numpy %.3f' % (
random.random(), torch.rand(1)[0], np.random.rand())) | 44,189 |
def most_seen_creators(event_kind=None, num=10):
"""
Returns a QuerySet of the Creators that are associated with the most Events.
"""
return Creator.objects.by_events(kind=event_kind)[:num] | 44,190 |
def use_memmap(logger, n_files=1):
"""Memory-map array to a file, and perform cleanup after.
.. versionadded:: 0.0.8
Parameters
----------
logger : :obj:`logging.Logger`
A Logger with which to log information about the function.
n_files : :obj:`int`, optional
Number of memory-m... | 44,191 |
async def test_activating_scene(hass):
"""Test the activation of a scene."""
calls = []
context = Context()
@callback
def record_call(service):
"""Add recorded event to set."""
calls.append(service)
hass.services.async_register(scene.DOMAIN, SERVICE_TURN_ON, record_call)
h... | 44,192 |
def _create_parser():
"""
@rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
parser.add_argument("tasks", help="perform specified task and all its dependencies",
metavar="task", nargs = '*')
parser.add_argument('-l', '--list-tasks', help = "List the ta... | 44,193 |
def sql_insert_account(con, vals):
"""
Insert a row/account into the accounts table.
param vals: (account, username, password, email, tag, iv, salt)
tag, iv, & salt are required for password decryption.
"""
cursor = con.cursor()
try:
cursor.execute("""
INSERT INT... | 44,194 |
def _verify_all_states_reachable(states_list):
"""Verifies that all states are reachable from the initial state."""
# This queue stores state names.
processed_queue = []
curr_queue = [states_list[0]['name']]
while curr_queue:
curr_state = curr_queue[0]
curr_queue = curr_queue[1:]
... | 44,195 |
def test_merge_strategy_merge_state_top_saltenv_foo(dunder_opts):
"""
This tests with state_top_saltenv=foo, which should pull states *only*
from the foo saltenv. Since that top file is only authoritative for
its own saltenv, *only* the foo saltenv's matches from the foo top file
should be in the re... | 44,196 |
def gauss_to_post(trainer: IvectorExtractorTrainer) -> None:
"""
Multiprocessing function that does Gaussian selection and posterior extraction
See:
- http://kaldi-asr.org/doc/gmm-global-get-post_8cc.html
- http://kaldi-asr.org/doc/scale-post_8cc.html
for more details
on the Kaldi binary ... | 44,197 |
def read_lexicon():
"""
Returns the dict of {'word': string, 'score': int} represented by lexicon.txt
"""
return read_dict('resources/lexicon.txt') | 44,198 |
def get_usd_qt_path():
"""
Returns path where USD Qt files are located
:return: str
"""
from tpDcc.libs.python import path
platform_dir = get_platform_path()
if not platform_dir or not os.path.isdir(platform_dir):
LOGGER.warning('No USD platform directory found: "{}"'.format(platfo... | 44,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.