content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def as_jenks_caspall_sampled(*args, **kwargs):
"""
Generate Jenks-Caspall Sampled classes from the provided queryset. If the queryset
is empty, no class breaks are returned. For more information on the Jenks
Caspall Sampled classifier, please visit:
U{http://pysal.geodacenter.org/1.2/library/esda/m... | 5,000 |
def testToID() -> None:
"""Tests the toID() function
"""
assert psclient.toID("hi") == "hi"
assert psclient.toID("HI") == "hi"
assert psclient.toID("$&@*%$HI ^4åå") == "hi4" | 5,001 |
def positive_dice_parse(dice: str) -> str:
"""
:param dice: Formatted string, where each line is blank or matches
t: [(t, )*t]
t = (0|T|2A|SA|2S|S|A)
(note: T stands for Triumph here)
:return: Formatted string matching above, except tokens are ... | 5,002 |
def fmt_title(text):
"""Article title formatter.
Except functional words, first letter uppercase. Example:
"Google Killing Annoying Browsing Feature"
**中文文档**
文章标题的格式, 除了虚词, 每个英文单词的第一个字母大写。
"""
text = text.strip()
if len(text) == 0: # if empty string, return it
return text
... | 5,003 |
def insn_add_off_drefs(*args):
"""
insn_add_off_drefs(insn, x, type, outf) -> ea_t
"""
return _ida_ua.insn_add_off_drefs(*args) | 5,004 |
def lambda_handler(event, context):
"""Lambda function that responds to changes in labeling job status, updating
the corresponding dynamo db tables and publishing to sns after a job is cancelled.
Parameters
----------
event: dict, required API gateway request with an input SQS arn, output SQS arn
... | 5,005 |
def get_answer(question: Union[dns.message.Message, bytes],
server: Union[IPv4Address, IPv6Address],
port: int = 53,
tcp: bool = False,
timeout: int = pydnstest.mock_client.SOCKET_OPERATION_TIMEOUT) -> dns.message.Message:
"""Get an DNS message with answer... | 5,006 |
def test_parse_input_update_rules_A():
"""
`parse_input_update_rules`
Feature A: parsing predecessor node lists and truth tables from
proper input.
"""
# Test for {no invalid Python node names, invalid Python node names}.
node_name_1 = 'A'
node_name_2 = '1A'
# Test for {lowercase... | 5,007 |
def intersectionPoint(line1, line2):
"""
Determining intersection point b/w two lines of the form r = xcos(R) + ysin(R)
"""
y = (line2[0][0]*np.cos(line1[0][1]) - line1[0][0]*np.cos(line2[0][1]))/(np.sin(line2[0][1])*np.cos(line1[0][1]) - np.sin(line1[0][1])*np.cos(line2[0][1]))
x = (line1[0][0] - ... | 5,008 |
def iter_sequences_bam(bamfile):
"""Iterate over sequences in a BAM file. Only outputs the sequence, useful
for kmerizing."""
bam = pysam.AlignmentFile(bamfile, check_header=False, check_sq=False)
seq_iter = iter(bam.fetch(until_eof=True))
seq_iter = filter(lambda r: not r.is_qcfail, seq_iter)
... | 5,009 |
def test_datadir_rootdir(tmp_path: Path):
"""
Tests datadir/rootdir discovery, for
a datadir.txt in the same directory and in
a parent directory.
"""
(tmp_path / 'root').mkdir()
(tmp_path / 'root' / 'inner').mkdir()
(tmp_path / 'data').mkdir()
with (tmp_path / 'root' / 'datadir.txt')... | 5,010 |
def _remove_keywords(d):
"""
copy the dict, filter_keywords
Parameters
----------
d : dict
"""
return { k:v for k, v in iteritems(d) if k not in RESERVED } | 5,011 |
def build_trib_exp(trib_identifier, trib_key_field):
"""Establishes a SQL query expresion associating a given tributary id"""
return '"{0}"'.format(trib_key_field) + " LIKE '%{0}%'".format(trib_identifier) | 5,012 |
def train_epoch(loader, vae, optimizer, device, epoch_idx, log_interval,
loss_weights, stats_logger, clip_gradients=None):
"""Train VAE for an epoch"""
vae.train()
train_losses = {}
train_total_loss = 0
for batch_idx, data in enumerate(loader):
data = data.to(device)... | 5,013 |
def test_environment():
"""Creates a test environment to check if everything is ok"""
game, actions = create_environment(visible=True)
game.new_episode()
while not game.is_episode_finished():
action = random.choice(actions)
game.make_action(action)
print("Total reward:", game.get_tot... | 5,014 |
def phased_multi_axes(times, data, std, ephemeris, thin=1,
colours='midnightblue', ylim_shrink=0.8,
subplot_kw=None, gridspec_kw=None, **kws):
"""
Parameters
----------
times
data
std
ephemeris
thin
colours
subplot_kw
gridspec_kw
... | 5,015 |
def get_delta(K):
"""This function returns the delta matrix needed calculting Pj = delta*S + (1-delta)*(1-S)
Args:
inputs:
K: Integers below 2^K will be considered
outputs:
delta: Matrix containing binary codes of numbers (1, 2^K) each one arranged ro... | 5,016 |
def string_split_readable(inp, length):
"""
Convenience function to chunk a string into parts of a certain length,
whilst being wary of spaces.
This means that chunks will only be split on spaces, which means some
chunks will be shorter, but it also means that the resulting list will
only conta... | 5,017 |
def convertFormat(sequence):
"""convert a genbank file to a fasta format file"""
for seq_record in SeqIO.parse(sequence, "genbank"):
count = SeqIO.convert(sequence, "genbank", "%s.fasta" %seq_record.id, "fasta")
print("Converted %i records" % count) | 5,018 |
def get_similarity_transform_matrix(
from_pts: torch.Tensor, to_pts: torch.Tensor) -> torch.Tensor:
"""
Args:
from_pts, to_pts: b x n x 2
Returns:
torch.Tensor: b x 3 x 3
"""
mfrom = from_pts.mean(dim=1, keepdim=True) # b x 1 x 2
mto = to_pts.mean(dim=1, keepdim=True) ... | 5,019 |
def get_current_daily_puzzle(**kwargs) -> ChessDotComResponse:
"""
:returns: ``ChessDotComResponse`` object containing
information about the daily puzzle found in www.chess.com.
"""
return Resource(
uri = "/puzzle",
top_level_attr = "puzzle",
**kwargs
) | 5,020 |
def logger_error(message: str) -> None:
"""Adds an error message to the log file. This is used for reporting errors in
the program that occur that do not prevent the program from working."""
# Sets the config for the logger.
logging.basicConfig(filename='../pysys.log', level=logging.DEBUG, format=FO... | 5,021 |
def stroke_negative():
"""
render template if user is predicted negative for stroke
"""
return render_template("negative.html") | 5,022 |
def default_data(sim_type):
"""New simulation base data
Args:
sim_type (str): simulation type
Returns:
dict: simulation data
"""
import sirepo.sim_data
return open_json_file(
sim_type,
path=sirepo.sim_data.get_class(sim_type).resource_path(f'default-data{sirepo... | 5,023 |
def get_instance_name_to_id_map(instance_info):
"""
generate instance_name to instance_id map.
Every instance without a name will be given a key 'unknownx', where x is an incrementing number of instances without a key.
"""
instance_name_to_id = {}
unknown_instance_count = 0
for instance_id ... | 5,024 |
def log_get_stdio_record(log):
"""
Returns a darshan log record for STDIO.
Args:
log: handle returned by darshan.open
Returns:
dict: log record
"""
return log_get_generic_record(log, "STDIO", "struct darshan_stdio_file **") | 5,025 |
def gits_set_profile(args):
"""
Function that prints hello message
to user console
"""
# print(args.email)
# print("Hello from GITS Commandline Tools-Profile")
try:
# check regex
check_val = check(args.email)
# print(check_val)
if check_val:
proce... | 5,026 |
def generate_spiral2d(nspiral=1000,
ntotal=500,
nsample=100,
start=0.,
stop=1, # approximately equal to 6pi
noise_std=.1,
a=0.,
b=1.,
savefig=T... | 5,027 |
def AUC_confidence(auc_value, num, interval=0.95):
"""
Calculate upper and lower 95% CI for area under the roc curve
Inspired by https://stats.stackexchange.com/questions/18887
:param r: spearman's rho
:param num: number of data points
:param interval: confidence interval (0-1.0)
:return: l... | 5,028 |
def add_data(data):
""" This adds data """
item = data
db.insert(data)
return 'chain updated' | 5,029 |
def detect_face(img_path, cc_path='../files/haarcascade_frontalface_default.xml'):
"""
Detect the face from the image, return colored face
"""
cc = cv2.CascadeClassifier(os.path.abspath(cc_path))
img_path = os.path.abspath(img_path)
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.CO... | 5,030 |
def build_node_to_name_map(head):
"""
:type head: DecisionGraphNode
:return:
"""
node_to_name_map = {}
name_to_next_idx_map = Counter()
def add_node_name(node):
assert node not in node_to_name_map
node_type_name = node.get_node_type_name()
idx = name_to_next_idx_m... | 5,031 |
async def test_first_does_not_kill(dut):
"""Test that `First` does not kill coroutines that did not finish first"""
ran = False
@cocotb.coroutine # decorating `async def` is required to use `First`
async def coro():
nonlocal ran
await Timer(2, units="ns")
ran = True
# Coro... | 5,032 |
def ReduceFloat(f, op=None):
"""Reduce a single float value over MPI"""
if not hasMPI:
raise Exception("mpi4py required for Reduce operations: not found")
if op is None:
op = MPI.SUM
fa = np.array([f]) # can only reduce over numpy arrays
MPI.COMM_WORLD.Allreduce(MPI.IN_PLACE,
... | 5,033 |
def GetVerificationStepsKeyName(name):
"""Returns a str used to uniquely identify a verification steps."""
return 'VerificationSteps_' + name | 5,034 |
def annotate_ms1_peaks(ms1_data, ms2_data, analyte_list):
"""Interpolate MS1 intensities for the time points for the MS2 scans for the largest mass peak in each analyte.
Use relative changes in intensity between interpolated MS1 data and real MS2 data to find MS2 peaks that go with
each analyte. """
ms2... | 5,035 |
def split_tblastn_hits_into_separate_genes(query_res_obj, max_gap):
"""Take a SearchIO QueryResult object and return a new object with hits
split into groups of HSPs that represent distinct genes. This is important,
because there may be multiple paralogous genes present in a single
nucleotide subject se... | 5,036 |
def to_entity_values(entity_group):
""" Parse current entity group content into a CreateEntity[]
"""
values = []
for _, row in entity_group.iterrows():
value = row[ENTITY_VALUE_COLUMN]
if not value: # Handle reserved entities
continue
synonyms = []
patterns ... | 5,037 |
def read_file(file_path):
"""
Read the contents of a file using utf-8 encoding, or return an empty string
if it does not exist
:param file_path: str: path to the file to read
:return: str: contents of file
"""
try:
with codecs.open(file_path, 'r', encoding='utf-8', errors='xmlcharref... | 5,038 |
def scrub(data):
"""
Reads a CSV file and organizes it neatly into a DataFrame.
Arguments:
data {.csv} -- the csv file to be read and scrubbed
Returns:
DataFrame -- the logarithmic returns of selected ticker symbols
"""
df = pd.read_csv(data, header=0, index_col=0, parse_dates=... | 5,039 |
def parse_args():
"""read arguments from command line
"""
parser = argparse.ArgumentParser(
description='preprocess.py',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset',
type=str,
nargs='?',
... | 5,040 |
def _get_lto_level():
"""
Returns the user-specific LTO parallelism level.
"""
default = 32 if config.get_lto_type() else 0
return read_int("cxx", "lto", default) | 5,041 |
def slice_label_rows(labeldf: pd.DataFrame, label: str, sample_list: List[str],
row_mask: NDArray[Any]) -> NDArray[Any]:
"""
Selects rows from the Pandas DataFrame of labels corresponding to the samples in a particular sample_block.
Args:
labeldf : Pandas DataFrame containing t... | 5,042 |
def rollback(var_list, ckpt_folder, ckpt_file=None):
""" This function provides a shortcut for reloading a model and calculating a list of variables
:param var_list:
:param ckpt_folder:
:param ckpt_file: in case an older ckpt file is needed, provide it here, e.g. 'cifar.ckpt-6284'
:return:
"""
... | 5,043 |
def read_interaction_file_mat(file):
"""
Renvoie la matrice d'adjacence associée au graph d'intéraction entre protéines ainsi que la liste
ordonnée des sommets
:param file: tableau contenant un graphe
:type file: dataframe
:return: une matrice d'adjascence de ce graphe et une liste ordonnée des ... | 5,044 |
def load_figures(fig_names):
"""
Uses a list of the figure names to load them into a list
@param fig_names:
@type fig_names:
@return: A list containing all the figures
@rtype: list
"""
fig_list = []
for i, name in enumerate(fig_names):
fig_list.append(pl.load(open(f"{name}.pi... | 5,045 |
def define_mimonet_layers(input_shape, classes, regularized=False):
"""
Use the functional API to define the model
https://keras.io/getting-started/functional-api-guide/
params: input_shape (h,w,channels)
"""
layers = { 'inputs' : None,
'down_path' : {},
'bottle_... | 5,046 |
def scattering_angle( sza, vza, phi, Expand=False, Degree=False ):
"""
Function scattering_angle() calculates the scattering angle.
cos(pi-THETA) = cos(theta)cos(theta0) + sin(theta)sin(theta0)cos(phi)
Input and output are in the unit of PI
Parameters
----------
sza: solar zenith angle is radian
... | 5,047 |
def _list_subclasses(cls):
"""
Recursively lists all subclasses of `cls`.
"""
subclasses = cls.__subclasses__()
for subclass in cls.__subclasses__():
subclasses += _list_subclasses(subclass)
return subclasses | 5,048 |
def main(from_json: bool = True, filename: str = DEFAULT_ARGS['pipeline_config_save_path']):
"""
Calls the specified pipeline.
:param filename: json filename
:param from_json: whether to run pipeline from json file or not
:return: pipeline call function
"""
# Parsing arguments
parser =... | 5,049 |
def put(url, **kwargs):
"""PUT to a URL."""
return session.put(url, **kwargs) | 5,050 |
def cod_records(mocker, cod_records_json):
"""Fixture for COD records metric instance."""
mocker.patch.object(RecordsMetric, 'collect',
new=records_collect(cod_records_json))
return metrics.records('cod_records', 'http://www.google.com') | 5,051 |
def _validate_cluster_spec(cluster_spec, task_type, task_id):
"""Validates `cluster_spec`.
It checks:
0) None of `cluster_spec`, `task_type`, and `task_id` is `None`.
1) task type is one of "chief", "worker" or "evaluator".
2) whether there is such a task type as `task_type` in the `cluster_spec`.
3) wheth... | 5,052 |
def add_computed_document_features(input_dict):
"""
TODO: Add a feature to Annotated Document Corpus.
:param adc: Annotated Document Corpus
:param feature_name: the name of new feature
:param feature_computation: "New Feature Computatation
:param feature_spec: Comma separated list of names of o... | 5,053 |
def get_lite_addons():
"""Load the lite addons file as a set."""
return set_from_file('validations/lite-addons.txt') | 5,054 |
def GetApexPlayerStatus_TRN(api_key, platform, playerName):
"""
Get the status of a player on Apex Legends.
:param api_key: The API key to use.
:param platform: The platform to use.
:param playerName: The player name to use.
"""
platform = _fixplatform(platform)
if _checkplatform(platfo... | 5,055 |
def subFactoryGet(fixture, **kwargs):
"""
To be used in fixture definition (or in the kwargs of the fixture constructor) to reference a other
fixture using the :meth:`.BaseFix.get` method.
:param fixture: Desired fixture
:param kwargs: *Optional:* key words to overwrite properties of this fixture
... | 5,056 |
def hello():
"""Return the dashboard homepage."""
return render_template('index.html') | 5,057 |
def create_subparsers(subparsers):
"""Create subparsers for run command"""
parser = subparsers.add_parser(
'extractpipenv', help="Run notebook and check if it reproduces the same results"
)
parser.set_defaults(func=extract, command=parser)
parser.add_argument("-p", "--path", type=str, defaul... | 5,058 |
def rapid_ping(client, dst_ip):
"""TODO: Docstring for ping.
:returns: TODO
"""
status = False
# run ping command with count 10 rapidly
command = 'exec cli ping ' + dst_ip + ' count 10 rapid'
stdin, stdout, stderr = client.exec_command(command, get_pty=True)
for line in iter(stdout.read... | 5,059 |
def test_data_dir():
"""
Returns path of test datas like excel
Used for test or notebook
"""
path = Path(__file__).parent.parent / 'testdata'
return path | 5,060 |
def ingest_sequences(input_toml, click_loguru=None):
"""Marshal protein and genome sequence information."""
options = click_loguru.get_global_options()
user_options = click_loguru.get_user_global_options()
parallel = user_options["parallel"]
input_obj = TaxonomicInputTable(Path(input_toml), write_ta... | 5,061 |
def classify_audio(model, callback,
labels_file=None,
inference_overlap_ratio=0.1,
buffer_size_secs=2.0,
buffer_write_size_secs=0.1,
audio_device_index=None):
"""
Continuously classifies audio samples from the microph... | 5,062 |
def is_leap_year(year: int) -> bool:
"""Returns whether the given year is a leap year"""
if year % 100 == 0:
return year % 400 == 0
else:
return year % 4 == 0 | 5,063 |
def find_manifests(pkgnames, verbose=True):
""" return a dictionary keyed by pkgname with the found manifest's full path """
(abspath, dirname) = (os.path.abspath, os.path.dirname)
(ret,stdout,stderr) = spawn("git rev-parse --show-toplevel")
root = stdout[0] if ret == 0 else os.getcwd()
jsonfiles = ... | 5,064 |
def prepare_nginx_certs(cert_key_path, cert_path):
"""
Prepare the certs file with proper ownership
1. Remove nginx cert files in secret dir
2. Copy cert files on host filesystem to secret dir
3. Change the permission to 644 and ownership to 10000:10000
"""
host_ngx_cert_key_path = Path(os.p... | 5,065 |
def is_valid_distribution(qk: np.ndarray, axis: int) -> bool:
"""valid is e.g.: [], [1.0], [0.5, 0.5]"""
"""not valid is e.g.: [-1.0], [0.6, 0.6], [np.nan], [np.nan, 0.6], [1.2]"""
assert 0 <= axis < len(qk.shape)
if qk.shape[axis] == 0:
return True
if np.any(qk < 0.0):
return False
if np.any(qk > 1... | 5,066 |
def test_did_to_bytes():
"""Tests did to bytes conversion."""
id_test = secrets.token_hex(32)
did_test = "did:op:{}".format(id_test)
id_bytes = Web3.toBytes(hexstr=id_test)
assert did_to_id_bytes(did_test) == id_bytes
assert did_to_id_bytes(id_bytes) == id_bytes
with pytest.raises(ValueErr... | 5,067 |
def srt(data, cube, **kwargs):
"""
Define Solar Rotational Tomography model with optional masking of
data and map areas. Can also define priors.
Parameters
----------
data: InfoArray
data cube
cube: FitsArray
map cube
obj_rmin: float
Object minimal radius. Ar... | 5,068 |
def get(status_id):
"""Fetches a status of previously submitted PushFunds request.
Returns a status of :func:`~pyvdp.visadirect.fundstransfer.MultiPushFundsTransactionsModel` request by transaction
identifier, returned with 202 response.
:param str status_id: **Required**. Transaction status id... | 5,069 |
def onInit():
""" Do everything that is needed to initialize processing (e.g.
open files, create handles, connect to systems...)
"""
print "onInit" | 5,070 |
def do_image_tag_update(gc, args):
"""Update an image with the given tag."""
if not (args.image_id and args.tag_value):
utils.exit('Unable to update tag. Specify image_id and tag_value')
else:
gc.image_tags.update(args.image_id, args.tag_value)
image = gc.imag... | 5,071 |
def getLocalDir(jobdir, dirname=''):
"""
Assemble destination directory for job results.
Raises:
TargetDirExistsError: Destination for job results already exists.
"""
if dirname:
dstDir = os.path.join(dirname, jobdir)
else:
dstDir = os.path.join(os.getcwd(), jobdir)
... | 5,072 |
def eval_pop_thread(args):
"""
Evaluates solutions, returns a list of floats, between 0 and 1
(probabilities of survival and reproduction).
"""
m_solutions, m_state_hash_table, id_mi = args[0], args[1], args[2]
step = int(N_POP/N_PROC)
prob_surv = np.zeros(step)
for index_sol in range(le... | 5,073 |
def test_sophos_firewall_ip_host_group_list_command(requests_mock):
"""
Scenario: List all IP host groups.
Given:
- User has provided valid credentials.
When:
- sophos_firewall_ip_host_group_list is called.
Then:
- Ensure number of items is correct.
- Ensure outputs prefix is cor... | 5,074 |
def _mini_batch_convergence(model, iteration_idx, n_iter, tol,
n_samples, centers_squared_diff, batch_inertia,
context, verbose=0):
"""Helper function to encapsulate the early stopping logic"""
# Normalize inertia to be able to compare values when
# ba... | 5,075 |
def setfig(fig,**kwargs):
"""Tim's handy plot tool
"""
if fig:
pl.figure(fig,**kwargs)
pl.clf()
elif fig==0:
pass
else:
pl.figure(**kwargs) | 5,076 |
def test_incremental_file_insert(tmp_path):
"""Test inserting text into a file."""
temp_file = tmp_path / "output.txt"
test_file = fixture_dir / "pipeline_dag_test.md"
temp_file.write_text(test_file.read_text())
writer = file_processing.IncrementalFileInsert(str(temp_file), r"(?im)^## \d+\.\d+\.\d... | 5,077 |
def update_user(BrokerId=None, ConsoleAccess=None, Groups=None, Password=None, Username=None):
"""
Updates the information for an ActiveMQ user.
See also: AWS API Documentation
Exceptions
:example: response = client.update_user(
BrokerId='string',
ConsoleAccess=True|False,
... | 5,078 |
def rho_MC(delta, rhoeq=4.39e-38):
"""
returns the characteristic density of an
axion minicluster in [solar masses/km^3]
forming from an overdensity with
overdensity parameter delta.
rhoeq is the matter density at matter
radiation equality in [solar masses/km^3]
"""
return 140 * (1 + del... | 5,079 |
def _parse_parameter_from_value(
string: str,
parameter_to_wordlist_mapping: Dict[Union[TimeResolution, PeriodType, Parameter], List[List[str]]]
) -> Optional[Union[TimeResolution, PeriodType, Parameter]]:
"""
Function to parse a parameter from a given string based on a list of parameter enumera... | 5,080 |
def start(mainGuiClass, **kwargs):
"""This method starts the webserver with a specific App subclass."""
debug = kwargs.pop('debug', False)
standalone = kwargs.pop('standalone', False)
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
format='%(name)-16s %... | 5,081 |
def test_list_ncname_min_length_4_nistxml_sv_iv_list_ncname_min_length_5_4(mode, save_output, output_format):
"""
Type list/NCName is restricted by facet minLength with value 10.
"""
assert_bindings(
schema="nistData/list/NCName/Schema+Instance/NISTSchema-SV-IV-list-NCName-minLength-5.xsd",
... | 5,082 |
def AffineMomentsF(I, returnShape=False):
"""
Input: - I: A 2D image
Output: - Out: A (1x6) vector containing 6 moment features
"""
# ************************************************************************
# Modified for MRI feature extraction by the Department of Diagnostic
# and ... | 5,083 |
def render(scene):
"""
:param scene: Scene description
:return: [H, W, 3] image
"""
# Construct rays from the camera's eye position through the screen coordinates
camera = scene['camera']
eye, ray_dir, H, W = generate_rays(camera)
# Ray-object intersections
scene_objects = scene['ob... | 5,084 |
def state_fidelity(state1, state2):
"""Return the state fidelity between two quantum states.
Either input may be a state vector, or a density matrix. The state
fidelity (F) for two density matrices is defined as::
F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2
For a pure state and m... | 5,085 |
def linear_regression(x,y,title='',xlabel='X',ylabel='Y'):
"""Does simple linear regression"""
b = estimate_coef(x, y)
print("Estimated eqauation:\ny = %s + %s*x + e"%(b[0], b[1]))
x_a,y_a = give_time_series(x,y)
plot_regression_line(x_a, y_a, b, title=title,xlabel=xlabel,ylabel=ylabel) | 5,086 |
def process_state(request):
"""Procesa una request GET o POST para consultar datos de provincias.
En caso de ocurrir un error de parseo, se retorna una respuesta HTTP 400.
Args:
request (flask.Request): Request GET o POST de flask.
Returns:
flask.Response: respuesta HTTP
"""
r... | 5,087 |
def is_ascii(string):
"""Return True is string contains only is us-ascii encoded characters."""
def is_ascii_char(char):
return 0 <= ord(char) <= 127
return all(is_ascii_char(char) for char in string) | 5,088 |
def _get_predictions_from_data(
model: Union[Model, SKLEARN_MODELS],
data: Union[
tf.data.Dataset,
Tuple[Inputs, Outputs],
Tuple[Inputs, Outputs, Paths],
],
batch_size: Optional[int],
tensor_maps_in: Optional[List[TensorMap]],
tensor_maps_out: Optional[List[TensorMap]],
)... | 5,089 |
def process_ud_treebank(treebank, udbase_dir, tokenizer_dir, short_name, short_language, augment=True):
"""
Process a normal UD treebank with train/dev/test splits
SL-SSJ and other datasets with inline modifications all use this code path as well.
"""
prepare_ud_dataset(treebank, udbase_dir, tokeni... | 5,090 |
def execute():
"""Set default module for standard Web Template, if none."""
vmraid.reload_doc('website', 'doctype', 'Web Template Field')
vmraid.reload_doc('website', 'doctype', 'web_template')
standard_templates = vmraid.get_list('Web Template', {'standard': 1})
for template in standard_templates:
doc = vmraid... | 5,091 |
def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height):
"""
Read and return the viewport data
"""
VIEW_PATH = '../../Viewport/'
view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user{}'.format(dataset, dataset, topic, usernum), 'rb'), ... | 5,092 |
def MinimizeParameters(metaTemplate, parametersLines, noOfAttributes):
""" Reduces the number of parameters required by replacing different parameters with a single parameter if they agree on all devices."""
lineParamMap = {}
for block in metaTemplate.blocks:
for line in block.lines:
fo... | 5,093 |
def test_binarytree_repr_as_expected():
""" After instantiating with a list, does the BinaryTree repr look right
"""
input = [13, 42, 7]
expected = '<BinaryTree | Root: 13>'
r = BinaryTree(input)
actual = repr(r)
assert expected == actual | 5,094 |
def tail_owner_changed(tail, owner_func):
"""This hook is for when a chunk is moved to another function and is for older versions of IDA.
We simply iterate through the new chunk, decrease all of its tags in its
previous function's context, and increase their reference within the new
function's context.... | 5,095 |
def getListGroups(config):
"""
Get list of groups
"""
print("Retrieve list of group")
data = None
grpList = None
__grpList = gitlabGroupList()
if (DUMMY_DATA):
curDir = os.path.dirname(os.path.abspath(__file__))
testFile = getFullFilePath(GROUPS_TEST_FILE)
with o... | 5,096 |
def call(args, version):
"""Converts callList into functionString."""
# Find keyword
keywords = [i for i in args if i in Variables.keywords(version)]
# Too many keywords is a syntax error.
if len(keywords) > 1:
raise UdebsSyntaxError("CallList contains to many keywords '{}'".format(args))
... | 5,097 |
def get_object_locations(obj_refs: List[ObjectRef], timeout_ms: int = -1
) -> Dict[ObjectRef, Dict[str, Any]]:
"""Lookup the locations for a list of objects.
It returns a dict maps from an object to its location. The dict excludes
those objects whose location lookup failed.
Ar... | 5,098 |
def remove_host(plateform=None, name=None, environment=None):
""" Remove Host Object from Platform Object attribute hosts and return updated Platform Object.
:param: plateform: host's plateform (same as type yaml file) passed by user
:param: name: host's name passed by user
:param: name: ho... | 5,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.