content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def qt4_to_mpl_color(color):
"""
Convert a QColor object into a string that matplotlib understands
Note: This ignores opacity
:param color: QColor instance
*Returns*
A hex string describing that color
"""
hexid = color.name()
return str(hexid) | 3b885562a7e4c1889c14291dfa047715fdf9a440 | 664,666 |
import random
def quicksort_original(data):
"""
Ops: O(n log n), worst case: O(n^2)
"""
if len(data) <= 1:
return data
else:
q = random.choice(data)
s_data = []
m_data = []
e_data = []
for n in data:
if n < q:
s_data.appen... | 6531b5bef9315a0ce457903759fac6256f699dec | 664,667 |
def get_columns(connection, table):
"""Function to get columns information."""
sql = 'DESCRIBE ' + table + ';'
result = connection.execute(sql)
columns = list()
for row in result:
column_name = row[0]
column_type_and_size = row[1].split('(')
column_type = column_type_and_siz... | 769f7e9e923fd7f85228b91cb65e7076bed71c35 | 664,668 |
import os
def get_installed_games(libraries):
"""Returns dictionary where keys are APP_IDs and values are names of installed games."""
found_games = {}
for library in libraries:
files = next(os.walk(library + '/steamapps'))[2]
for filename in files:
if 'appmanifest' in filename... | f801b50a8d3715d3d3e93f2c2fef8b9077a6a9c7 | 664,669 |
import subprocess
def version_compare(a, b):
"""Compare the given versions.
Call out to ``dpkg`` to make sure the code doing the comparison is
compatible with what the ``apt`` library would do. Mimic the return
values.
Upstream reference:
https://apt-team.pages.debian.net/python-apt/library/a... | 50e41261d3c2f2a784b1d384ebe68e574977c050 | 664,670 |
def scale_yaxis(dataset, scale):
"""The dataset supplied is scaled with the supplied scale. The scaled
dataset is returned."""
result = {}
result["data"] = [x / scale["scale"] for x in dataset]
result["format"] = scale["label"]
return result | 3c8cc66ada08067d5bd6a295e59a649172839783 | 664,671 |
def public(fun, scope=None):
"""
Functions that allow any client access, including those that haven't logged
in should be wrapped in this decorator.
:param fun: A REST endpoint.
:type fun: callable
:param scope: The scope or list of scopes required for this token.
:type scope: str or list o... | b3146486c5d335117d9447605b0c9dc0bfdfaeb4 | 664,673 |
def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... | da8d2a10642ceec36bfd6cdfec63c516c38fa2cb | 664,675 |
def divide_separate_words(X):
"""
As part of processing, some words obviously need to be separated.
:param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return:
>>> divide_separate_words([['ita vero'], ['quid', 'est', 'veritas']])
[['ita', 'vero'], ['q... | 69a6887f562629d2b82d3302fa61ce3c7a7dd791 | 664,677 |
def resize(image, size, resize_image_pl, resize_shape_pl, resize_op, session):
"""
Performs resizing of image.
:param image: Image to resize.
:param size: Size of resized image.
:param resize_image_pl: Resize operation input tensor.
:param resize_shape_pl: Resize operation shape input t... | 943d158ee4ca21fb039e388bb8b36bc5d4434798 | 664,678 |
import os
def create_dataset_locally(file: bytes, filename: str = "file", name: str = "file", path: str = "/tmp/data"):
"""Creates a dataset from a CSV and writes locally.
Args:
file (bytes): file object content.
filename (str, optional): original file name. Defaults to "file".
name (... | 28c9ab38adc2bfb6d1b427346c14a393606d9010 | 664,679 |
def ilcode(msg: str):
"""Format to inline markdown code"""
return f'`{msg}`' | 64205d05c9260a94cc18dd0c1bc08663ad11d6ec | 664,680 |
def is_video_frame_size(x, y, w, h, threshold=200):
"""check video frame size.
DVD 68:95
"""
width = w - x
height = h - y
# 68:95 = width:height -> height = (95 * width) / 68
_height = (95 * width) / 68
loss = height - _height
if threshold > abs(loss):
return True
... | d15f9b6fc2c48c572bb38ff4ebae142f6522ae05 | 664,681 |
def opaque_legend(ax, fontsize=None, handler_map=None):
"""
Calls legend, and sets all the legend colors opacity to 100%.
Returns the legend handle.
"""
leg = ax.legend(fontsize=fontsize, handler_map=handler_map)
for lh in leg.legendHandles:
fc_arr = lh.get_fc().copy()
fc_arr[:, ... | 585188d19062a050878208133a06f6e93f8928fd | 664,682 |
def _requirement_to_str_lowercase_name(requirement):
"""
Formats a packaging.requirements.Requirement with a lowercase name.
This is simply a copy of
https://github.com/pypa/packaging/blob/16.8/packaging/requirements.py#L109-L124
modified to lowercase the dependency name.
Previously, we were i... | 83a7d1b825d32456066dfe9b0e79fa08a2ed9444 | 664,683 |
import re
def to_snake_case(value: str) -> str:
"""
Convert camel case string to snake case
:param value: string
:return: string
"""
first_underscore = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', first_underscore).lower() | 9ca9eb70dfcbce50b99a206442426492f1c99fd1 | 664,684 |
from typing import Union
from typing import List
from typing import cast
def as_multiclass(
y: Union[List[str], List[List[str]]], is_multilabel: bool
) -> List[str]:
"""
Returns:
Labels in multiclass format, validated against
possible mismatch between the multilabel attribute and data format.
... | 63acb56209a52a8db4db33cfec9b0f8077bf1840 | 664,686 |
def alnum(string, alt='_', trim=False, single=False):
"""Replace non alpha numeric characters with *alt*. If *trim* is **True**
remove preceding and trailing *arg* characters. If *single* is **True**,
contain only a single joining *alt* character. """
result = ''
multi = not bool(single)
prev... | 8cff96608f0760e74fcdceae9d1d0d213825a81d | 664,687 |
def is_singleline_comment_start(code, idx=0):
"""Position in string starts a one-line comment."""
return idx >= 0 and idx+2 <= len(code) and code[idx:idx+2] == '//' | 21a4b65ec923c5a87e510614f88bbb93ccff87b3 | 664,689 |
import os
import mimetypes
def file_type(key: str) -> str:
"""
Return file extension to MIME types
:return: file extension MIME type as string
"""
# extract file extension in file name string
file_info = os.path.splitext(key)
file_extension = file_info[1].lower()
try:
return m... | df9aeb74f14ba23bb7683feda5eee9a9539676f1 | 664,692 |
def validate_signal_tracer_headers(df):
"""Validate that headers are correct"""
expected_headers = ["Chromosome", "Window", "Sample", "Value"]
try:
assert list(df.columns) == expected_headers
return True
except AssertionError:
return False | 8ed0a72cf90d3027274810602fa0c918249b6b0b | 664,693 |
def unique(elements):
"""
Removes duplicate elements from a list of elements.
"""
return list(set(elements)) | 831983be502d37c3900f4dad36b47773380fe740 | 664,694 |
def _underline(text):
"""Format a string by overstriking."""
return ''.join('_' + '\b' + ch for ch in text) | e6f3ebc5744de35e079009ab884140990ca6a813 | 664,695 |
def notasR(nota, ok=False):
"""
-> Função para analisar notas e situações de vários alunos
:param nota: uma lista de notas
:param ok: valor opcional, indicando deve ou não adicionar a situação.
:return: dicionário com várias informações da turma.
"""
notas = {}
cont = maior = menor = som... | 21c5114772328c929c5c42f7a606b21fb2052bab | 664,696 |
def gql_users(fragment):
"""
Return the GraphQL users query
"""
return f'''
query($where: UserWhere!, $first: PageSize!, $skip: Int!) {{
data: users(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
''' | 808bbe24848e21c572800403de17291312292502 | 664,697 |
import sympy
def Compute_LHS(rhs, testfunc, dofs, do_simplifications=False):
"""
This computes the LHS matrix.
Keyword arguments:
- rhs -- The RHS vector
- testfunc -- The test functions
- dofs -- The dofs vectors
- do_simplifications -- If apply simplifications
"""
lhs = sympy.Ma... | 59e82e1f7396f50a688cebf03a4726f5721f99d2 | 664,698 |
def perturb_overlap_obs(perturbation_list,adata_here,list_name):
"""Get perturbations present as obs
"""
found_perturbations=[]
count_perturbations=0
for perturbation in perturbation_list:
if perturbation not in adata_here.obs:
print('Warning: '+perturbation+' is not in the pr... | 3f85caf8a8250862e0c148cc876e298c845c53a6 | 664,699 |
def get_route_policy(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get route policy configurations from Edge Connect appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - routePolicy
- GET
- GET /route... | 5b6c7654602c198570c710492c311eb9de51a024 | 664,700 |
def clean_exclusive_presets(parser, preset, remaining_argv):
"""Modifies the presets dictionary in-place to remove any defaults that would violate
a mutually exclusive constraint."""
def mutually_exclusive_action_on_cmd(group):
for action in group._group_actions:
if any([opt in remaining... | 384466838803c66f94d865654e550d8b12435cc8 | 664,701 |
def inline_formatting_preparation(self, word, position, code_flag, bold_flag, italic_flag):
"""Recognizes HTML formatting substrings at the start / end of a given word.
Sets and returns all necessary flags.
Warning: There can only be one type of format active at the same time.
Overloading the ... | ef6512b206c83938fc1bac6c2a72c139e44899c0 | 664,702 |
def change_categorical_value(df, new_name, old_values, col):
"""
replace categorical values in `old_values` with `new_name`
in given `col` of `df`
Parameters
----------
df: pandas.DataFrame
new_name: STR
old_values: LIST
col: STR
Returns
-------
DataFrame
... | 09e856ec0fe0f1206ad611d451a8921ea9eabedd | 664,703 |
def vcf_get_columns(vcf):
"""Return columns as "SAMPLE_ID"."""
return vcf["samples"] | 66e28ff264348960d46f5fe35ec26b51da48a11d | 664,704 |
def del_empty(list):
"""deletes empty elements in lists"""
for x in range(len(list)):
if len(list[x - 1]) == 0:
del list[x - 1]
return list | 2db2f93331b1db3d711f065f0ec87a7f8b479eb9 | 664,705 |
def get_V_col_j_d_t(V_fan_P0_j, A_col_j, A_col):
"""空気搬送ファン稼働時に集熱器群jを流れる空気の体積流量 (m3/h) (24)
Args:
V_fan_P0_j(float): 空気搬送ファンの送風機特性曲線において機外静圧をゼロとしたときの空気搬送ファンの風量 (m3/h)
A_col_j(float): 集熱器群jの面積 (m2)
A_col(tuple): 集熱器群の面積 (m2)
Returns:
float: 空気搬送ファン稼働時に集熱器群jを流れる空気の体積流量 (m3/h)
""... | f959c6151215aaf12844344db1457a0455301497 | 664,706 |
import os
import time
import pickle
def read_data(folder, filename):
"""
Reads and returns the data from the data file after checking
if the file is already being accessed by another program
using the flag file
"""
flag_file = os.path.join(folder, str("flag_" + filename + ".txt"))
data_fi... | d676318fc731271da9bc5e6083d07b59ef7da76e | 664,707 |
def insert(s, c, pos):
"""
Returns the string s with character c inserted into position pos.
c can also be a string. If the position given is 0, c will be placed
at the beginning of the string. If the position given is len(s), c
will be placed at the end of the string. If pos is anything beyond thes... | 6f6cc81401de1bee5a1a1dfa5ddf1155aa94b625 | 664,708 |
async def read_stream_and_display(stream, display):
"""Read from stream line by line until EOF, display, and capture the lines."""
#import IPython; IPython.embed()
output = []
while True:
group = (await stream.read(79))
if not group:
break
output.append(group)
... | 60289f18af5a8dc092aefe9cbbb9700e79d6eee9 | 664,709 |
import argparse
def parse_cmd_options(argv):
"""parse command line"""
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=int, default=None)
parser.add_argument('--zero_shot_score', type=str, default=None,
help='could be: Zen (for Zen-NAS), TE (for TE-NAS)')
... | 67bc4b6b290293ae10f26f88890ccaba7e91265c | 664,710 |
def split_function_recursively(function):
"""
Example
-------
P1 = dl.VectorElement("Lagrange", mesh_2d.ufl_cell(), degree=1)
P2 = dl.FiniteElement("Lagrange", mesh_2d.ufl_cell(), degree=1)
V = FunctionSpace(V1*V2*V2).
P1*P2*P2 creates mixed spaces recursively so we must splir recursive... | b5687651b950c6444be025f6b2ffe5e13da8fc96 | 664,712 |
import numpy
def identity_matrix():
"""Return 4x4 identity/unit matrix.
>>> I = identity_matrix()
>>> numpy.allclose(I, numpy.dot(I, I))
True
>>> numpy.sum(I), numpy.trace(I)
(4.0, 4.0)
>>> numpy.allclose(I, numpy.identity(4))
True
"""
return numpy.identity(4) | da4d36db0829df448db307900ee922e3509e15d0 | 664,714 |
def creating_heatmap_data(dat):
"""
:param dat: dataframe
:rtype: dataframe
"""
data = dat[['date_time', 'number_of_vehicles']].groupby('date_time').sum().reset_index()
data['year'] = data['date_time'].apply(lambda row: row.year)
data['month'] = data['date_time'].apply(lambda row: row.month_... | a8bd1eeb12ae5dbf5623ce0732f74f00eebd464c | 664,715 |
import numpy as np
def q_to_a ( q ):
"""Returns a 3x3 rotation matrix calculated from supplied quaternion."""
# The rows of the rotation matrix correspond to unit vectors of the molecule in the space-fixed frame
# The third row a(3,:) is "the" axis of the molecule, for uniaxial molecules
# Use a to... | 0659101f88188b556b5699692bd38f888b10e45b | 664,716 |
def get_pos_value (my_pos, dict_tagset) :
"""Get the pos value"""
if my_pos in dict_tagset:
return dict_tagset[my_pos]
return 0 | d66bff7d6245fc14163e6d96f533413030455e1f | 664,717 |
import logging
def mixed_policy_with_expert(policy_network, expert_policy,
policy_params, alpha, x):
"""Rollout the mixed policy."""
logging.info("jit-ing mixed_policy_with_expert")
n_policies = len(policy_params)
ret = ((1 - alpha)**n_policies) * expert_policy(x)
for k, params ... | d655de976e54ba25363b4b59f0af618eee6657fb | 664,718 |
import torch
from typing import Union
def first_element(x: torch.Tensor, element: Union[int, float], dim: int = 1) -> torch.Tensor:
"""
Return indices of first occurence of element in x. If not found, return length of x along dim.
Based on https://discuss.pytorch.org/t/first-nonzero-index/24769/9
Ex... | 22b508463b3b82684c4d25679d4579b34a0cdbda | 664,719 |
import torch
def clip_pad_images(tensor, pad_shape, pad=0):
"""
Clip clip_pad_images of the pad area.
:param tensor: [c, H, W]
:param pad_shape: [h, w]
:return: [c, h, w]
"""
if not isinstance(tensor, torch.Tensor):
tensor = torch.as_tensor(tensor)
H, W = tensor.shape[1:]
h... | 70046287136e570c496280ea690186e21c67f8c5 | 664,720 |
def struct_from_buffer(cls, buf, offset, data_size, ptrs_size):
"""
Same as cls.from_buffer, but since Cython does not support classmethod,
at least this can be called from C
"""
self = cls.__new__(cls)
self._init_from_buffer(buf, offset, data_size, ptrs_size)
return self | ab1e3216a21d26b6ad20f5a8f04e89a97bdd483a | 664,721 |
import re
def check_legitimate_ver(version):
"""
This function check if the version is legitimate, only digits and dot.
:param version: str
:return: boolean
"""
return re.match("^[0-9.]+$", version) | 550e65b8deeb4c49562ace1cbf14b89c2d0818e5 | 664,723 |
def insertion_sort(array):
"""
Insertion Sort
Complexity: O(N^2)
"""
array_len = len(array)
for k in range(array_len):
temp = array[k]
i = k
while i > 0 and temp < array[i-1]:
array[i] = array[i-1]
i -= 1
array[i] = temp
return array | 09a9e5be73e23f42ee04129f979516e9e556a908 | 664,724 |
from typing import Optional
import pathlib
def find_locally(fname: str = "snap7") -> Optional[str]:
"""Finds the `snap7.dll` file in the local project directory.
Args:
fname: file name to search for. Optional.
Returns:
Full path to the `snap7.dll` file.
"""
file = pathlib.Path.cw... | b9fab1b8822a607782585a8dc4fabe51e82bce9c | 664,725 |
def countSuccess( successList, failList ):
"""Intended to be used with 'renewsliver', 'deletesliver', and
'shutdown' which return a two item tuple as their second
argument. The first item is a list of urns/urls for which it
successfully performed the operation. The second item is a
list of the urn... | fba276685c0f5bf85303b1c6025264cd3bb3bdaf | 664,728 |
from typing import Tuple
def find_padding_for_stride(
image_height: int, image_width: int, max_stride: int
) -> Tuple[int, int]:
"""Compute padding required to ensure image is divisible by a stride.
This function is useful for determining how to pad images such that they will not
have issues with div... | b181a75c38037c5efaf063772dd14b7be75ac48d | 664,729 |
def service(service, policy_settings):
"""
Service with prepared policy_settings added.
"""
service.proxy.list().policies.append(policy_settings)
return service | 7df83a4fec51f34e2f2fdca2e1edd6e42fc3c148 | 664,730 |
def calcBounds(array):
"""Calculate the bounding rectangle of a 2D points array.
Args:
array: A sequence of 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
if len(array) == 0:
return 0, 0, 0, 0
xs = [x for x, y... | b25f75a793c8cc2667b17c76bc0339a1da11af49 | 664,731 |
def set_title(title):
""" print title in a square box
To enhance the readability of the tests, this function prints in the
terminal teh string title in a square box.
Args:
title (str): the string
"""
space = " "
title = space + title + space
h_line = '+'
for character in... | 7090853f7b3e33095786b61b851c27d63199b57c | 664,732 |
def _get_enz_states(er_mech: str) -> list:
"""
Given a string with the enzyme mechanism written as a sequence of elementary reactions produces a list with the
enzyme state numbers and metabolites that bind/unbind to the respective enzyme states.
Args:
er_mech: string with elementary reactions t... | 0a2be33ce4a48a558b2fd9a0ef66d00742f45d76 | 664,733 |
def parse_stage_config(stage_cfg):
"""Parse config of STPP for three stages.
Args:
stage_cfg (int | tuple[int]):
Config of structured temporal pyramid pooling.
Returns:
tuple[tuple[int], int]:
Config of structured temporal pyramid pooling and
total numbe... | b7214f0822439cf069717574920e2653cd962178 | 664,734 |
import sys
def kernel_model(features, mode, params, scope=None):
"""Kernel models that allow interaction between question and context.
This is handler for all kernel models in this script. Models are called via
`params.model_id` (e.g. `params.model_id = m00`).
Function requirement for each model is in:
ht... | 46a7886e6258c5c2895e43f54ad4d8898c937c77 | 664,735 |
import uuid
def task_id():
"""Return a fake task_id."""
return str(uuid.uuid4()) | 3a007a9a1823b272f337a0278b322764510e3616 | 664,737 |
def redis_update_load_data_button(n):
"""
Let the user load the DRF data once they have chosen an input directory
"""
if n < 1: return True
return False | 63727a1e9da4165c0dad9c999be20389b4c374f3 | 664,738 |
import argparse
def parse_args():
"""Parse command line arguments.
Returns:
Arguments
"""
parser = argparse.ArgumentParser(description="Trains atlas reg mapping model.")
parser.add_argument(
"--organs_dir_path",
type=str,
default="data/data_organs",
help="Pa... | 6f8118ec86dd0ea7fc4394bdb98c66e6fed5c581 | 664,739 |
def create_fuel_blocks(pt0x, pt1x):
"""
Creates geometry for the fuel block with the following assumptions: Rectangular fuel source, Centered along the vertical axis of the combustion chamber, Width of fuel block is half the diameter of the combustion chamber, Assumed fuel height of 3 inches (0.0762 m), bottom... | 5bdbced7d59aa37fb3be8b61ddc580ef5fdc0919 | 664,740 |
import pathlib
def get_config_directory() -> pathlib.Path:
"""
Get the path to the config directory based off its location to this file. Up two directories, then into config
:return: Path pointing to the config directory
"""
return pathlib.Path(__file__).absolute().parent.parent.joinpath("config... | e4ab249e42db67117884746514c8e21a8d36a658 | 664,741 |
def egcd(a, b):
"""extended GCD
returns: (s, t, gcd) as a*s + b*t == gcd
>>> s, t, gcd = egcd(a, b)
>>> assert a % gcd == 0 and b % gcd == 0
>>> assert a * s + b * t == gcd
"""
s0, s1, t0, t1 = 1, 0, 0, 1
while b > 0:
q, r = divmod(a, b)
a, b = b, r
s0, s1, t0, t1... | 75f74a6fdfe03d512f88c81fa81a5f1bd4e91206 | 664,742 |
def get_absolute_url(obj, application_namespace=None):
"""
:param obj:
a instance of a model which inherits from AllinkBaseModel
:param application_namespace:
String, either defined in some urls.py file
or in most cases directly in a CMS-Page (e.g. news_engimatt or news_leafs)
:return:
t... | 9139c07e63171c98c91e8886199de546f8448fe7 | 664,744 |
def english_to_persian_number(number):
"""
converts a number from English alphabet to Persian alphabet. It is used because some students use Persian alphabet
in their student number and for each student number, we must check both English and Persian alphabet.
:param number: int or str
Number in... | 90dc5963d0c54e4928701a8f04b810c0021713e5 | 664,745 |
def _GetPackageName(module_name):
"""Returns package name for given module name."""
last_dot_idx = module_name.rfind('.')
if last_dot_idx > 0:
return module_name[:last_dot_idx]
return '' | eebbafe9a8e3014eae9279ad982794483e0c5515 | 664,746 |
def nldpost(self, label="", key="", fileid="", prefix="", **kwargs):
"""Gets element component information from nonlinear diagnostic files.
APDL Command: NLDPOST
Parameters
----------
label
Specifies the type of command operation:
EFLG - Element flag for nonlinear diagnostics.
... | f5209920bc3e2d5a799df66a0a5ade4be32f79ce | 664,747 |
def recursive_min(nxs):
"""
Find the maximum in a recursive structure of lists
within other lists.
Precondition: No lists or sublists are empty.
"""
smallest = None
first_time = True
for e in nxs:
if type(e) == type([]):
val = recursive_min(e)
else:
... | 5bf37edd7793c9202265c9ab7ad83379eb2b0b26 | 664,748 |
def add_empty_space(degrees) -> list:
"""
A degree like "Dipl.agr.biol." has no empty spaces between the grade of
the degree (Dipl.) and its specification (agr. biol.). To make sure that
both ways of writing are covered, the degree will be replicated as "Dipl.
agr. biol.".
"""
degrees_w_emp... | 44bdd7c1a7045e876cd786cd8a5373e5d7b39ca4 | 664,749 |
import subprocess
def captured_run(*args, **kwargs):
"""Run a subprocess and capture the output."""
proc = subprocess.run(
*args, **kwargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
return proc.returncode, proc.stdout, proc.stderr | 8cdf96f3f52977f4b360ff8e4a2ec793f19f3acc | 664,750 |
import textwrap
def public_doc(name: str, url: str) -> str:
"""Generate public module gallery docs from template."""
summary = f'This example was generated from `{name} source <{url}>`_'
summary = '\n'.join(textwrap.wrap(summary, width=79))
return f""".. _gallery-{name}:
{name}
{'=' * len(name)}
{sum... | 84e77bad4f2050b4c3abfa8155ed20aed6964cea | 664,751 |
def _format_list(param_name, list1, datadict, **kwargs):
"""Concatenate and format list items.
This is used to prepare substitutions in user-supplied args to the
various test invocations (ie: the location of flash).
Args:
@param param_name: The name of the item in `datadict`.
@param lis... | 756470f28817e33f94bf4aa798db691ac5e92ea0 | 664,752 |
import requests
from bs4 import BeautifulSoup
def make_request(url):
"""
Make the request and return a soup obj
:param url: the subito.it url
:return: a bs4 obj
"""
http_response = requests.get(url).text
return BeautifulSoup(http_response, 'html.parser') | 81fe071a35602c556113692872364790c6fa224b | 664,754 |
import argparse
def parse_args():
"""
Parses command line arguments.
"""
parser = argparse.ArgumentParser('Causality identification on AltLex')
parser.add_argument('--prepare', action='store_true',
help='create the directories, prepare the vocabulary and embeddings')
pa... | 6f15d670358206d5d60d848c1c23d41d713b733d | 664,755 |
def propagation_level_end(start_point: tuple, shape: tuple) -> int:
"""
Returns the maximum propagation level where our data points will change
I.e. if start_point=(8, 8, 8) and shape=(16, 16, 16), then returns 8
If start_point=(1, 1, 3) and shape=(16, 16, 16) then returns 16-1=15
"""
max_val = ... | 4558f286851261016e6c8f268622a91eb5640b86 | 664,757 |
def search(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
duplicate_nums = nums.copy() # list to list copy is a shallow copy and modifies the actual contents
duplicate_nums.sort()
for i in range(len(duplicate_nums)):
if duplicate_nums[i] == target:
... | 955e51c3bfb481d031325250d3ff43e0bc542df3 | 664,758 |
import csv
import logging
def load_csv_data(csv_file, transpose=False):
""" Load CSV data to list.
@param cvs_file: input CSV file path
@param transpose: transpose CSV data
@return: list object
"""
data_map = []
try:
data = []
with open(csv_file, 'r', encodin... | 0c961ef952d37a45e1b615d6b8fab4d308640ee5 | 664,759 |
def sum(mat, axis, target = None):
"""
Sum the matrix along the given dimension, where 0 represents the leading
dimension and 1 represents the non-leading dimension. If a target is
not prvided, a new vector is created for storing the result.
"""
return mat.sum(axis, target) | 105180c057bed95f2282ca168ec025fd06cf30e7 | 664,760 |
def insertion_sort(lista):
""" Retorna a lista ordenada usando o algoritmo InsertionSort.
"""
for j in range(len(lista))[1:]:
chave = lista[j]
i = j - 1
while i >= 0 and lista[i] > chave:
lista[i + 1] = lista[i]
i = i - 1
lista[i + 1] = chave
retur... | 101ebb5ab89ccf30b8255d5bd863c9187deda94c | 664,761 |
def truncate_xticklabels(plot, stop_index=30):
"""
Truncate xtick labels with an ellipsis after `stop_index`
"""
for label in plot.get_xticklabels():
t = label.get_text()
if len(t) < stop_index:
continue
else:
label.set_text(t[:stop_index] + '...')
... | 960448266e8dcdd5dcca593d70c9d612e8cec160 | 664,762 |
def list2str(l):
"""Convert list to matrix-string"""
s = ""
for i in range(len(l)):
s += "%.6e" % l[i]
if i < len(l) -1:
s += " "
return s | 92341ad343f66a1ad36ecab81072aa02af4622f6 | 664,764 |
import copy
def with_base_config(base_config, extra_config):
"""Returns dict with updates applied, helpful for one-liners"""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | 9afbc45a84047bcb8f971e8b486c0cca7cfd5644 | 664,765 |
def split_data(X, y, frac=0.7):
"""
Split data into test and train according to first axis
"""
frac = int(X.shape[0]* frac)
X_train, X_test = X[:frac], X[frac:]
y_train, y_test = y[:frac], y[frac:]
return X_train, X_test, y_train, y_test | 9f6919bbd11a973b5690c33366e33a12724df1da | 664,766 |
def fast_fib(n, memo={}):
"""
a recursive fib with memoization a.k.a dynamic programming
"""
if n < 2:
return 1
try:
return memo[n]
except KeyError:
memo[n] = fast_fib(n-1, memo) + fast_fib(n-2, memo)
return memo[n] | 36543d75c3c7e21454e59a6bc8f943abb5ff469b | 664,767 |
import pathlib
def replace_marker(text: str, marker: str, src_filename: str, replace_marker_with_src_file: bool = True) -> str:
""" replace a marker in the text with the content of a file, or with '' """
if replace_marker_with_src_file:
path_base_dir = pathlib.Path(__file__).parent
path_src_fi... | 1c8302f40fadde7b85e6bd13e84c4a5cb6e6ceac | 664,768 |
import bisect
def find_le(a, x):
"""Find rightmost value less than or equal to x"""
i = bisect.bisect_right(a, x)
if i:
return a[i-1]
raise ValueError | a2bdd7d6a63bbabaf64b86469852647627ac7d35 | 664,770 |
def _format_call(call, args):
"""
Return `call` formatted appropriately for `args`.
:param call: A pyconfig call object
:param args: Arguments from the command
:type call: :class:`_PyconfigCall`
"""
out = ''
if args.source:
out += call.annotation() + '\n'
if args.only_keys... | 085d1bccc3c816a57e25e6c4c291f7a7dfaa8ffb | 664,771 |
def from_uint8_bytes(uint8: bytes) -> int:
"""Convert from uint8 to python int."""
return int.from_bytes(uint8, byteorder="little") | cdabcd0d9fa16681ab89e11bb16d4c6a4d556024 | 664,772 |
def Precipitation(prec, temp, tt, rfcf, sfcf):
"""
========================================================
Precipitation (temp, tt, prec, rfcf, sfcf)
========================================================
Precipitaiton routine of the HBV96 model.
If temperature is lower than TT [degree C], ... | 5c6f92c73da5193e740a69ac26e5edbe52281fa3 | 664,773 |
import typing
import math
def triangle_ASA(alpha: float, c: float, beta: float) -> typing.Tuple[float, float, float]:
"""Given angle at A, included side A-B, angle at B of a plane triangle
this returns side A-C, angle at C, side C-B. Angles in radians.
See: https://en.wikipedia.org/wiki/Solution_of_triang... | 9858caf5875c0842ecd6120a80abcb504e574af5 | 664,774 |
def is_runway_visibility(item: str) -> bool:
"""Returns True if the item is a runway visibility range string"""
return (
len(item) > 4
and item[0] == "R"
and (item[3] == "/" or item[4] == "/")
and item[1:3].isdigit()
) | e463aeb4e4faf07ab0daeb45eff072add448225f | 664,775 |
import re
def ipv4_valid(ipv4):
"""
IPv4 validator
:param ipv4: [str] ipv4
:return:
"""
r = re.match(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", ipv4)
if r:
return True
else:
return False | 1e1d78c727b1017f37cb69bb9323fa97388feebd | 664,776 |
import optparse
def get_parser():
"""Parse args."""
parser = optparse.OptionParser()
parser.add_option(
"--device",
type="string",
dest="device_type",
help="Device Type. (Has to match the LVFPGA target plugin)",
default=None
)
parser.add_option(
"--i... | 9fc6e049a01c4b7fdb137b01cf4825a88dfd94f0 | 664,777 |
def format_seconds(seconds):
"""
https://stackoverflow.com/questions/538666/python-format-timedelta-to-string
"""
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('min', 60),
('sec', 1)
... | 94016e74207ce89771eb9079205ef81d8e06fb78 | 664,778 |
def E(expr):
"""
The notion of the expectation of random variables and the worst-case
expected values
Notes
-----
This function is used to denote
1. the expected value of an random variable when specifying the
uncertainty set of expectations.
2. the worst-case expected value of an a... | 70d23356c0e49e4decb9cd069f059af8a15104f2 | 664,779 |
from typing import List
from typing import Any
def get_from_list(array: List, index: int) -> Any:
"""try get from array"""
try:
return array[index]
except IndexError:
return None | ec3d611c7f14c8c1b63c9fe124210de216812e31 | 664,780 |
def secant(f, x0, x1, eps=5e-6, max_iterations=50):
"""
Function that finds a root using Secant method for a given function f(x). The function finds the root of f(x)
with a predefined absolute accuracy epsilon. The function excepts two starting points x0,x1 that belong to an
interval [a,b] in which is k... | 9cedc004842a56b7fb62af12affe77ff2db61a7f | 664,781 |
def ParamsSim():
"""
Return simulation parameters.
Returns
-------
pardict : Dictionary
Adaptation and simulation times and intervals.
"""
pardict={}
for var in ('adaptTime','adaptInt','runTime','runInt','sampling'):
pardict[var]=eval(var)
return pardict | 08d2c4d59d9a7bb1fb3eafb41197e6a83a2e4cc9 | 664,782 |
import yaml
from typing import OrderedDict
def ordered_load(stream):
""" Loads a .yml file, retaining the ordering of the file's
structure.
Args:
stream (file stream): Reference to readable .yml file
Returns:
(dict): Dictionary to create spectra config out of.
"""
class OrderedLo... | 4177956736dd21bab676fd14c91b53a08b6dcf1b | 664,783 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.