content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def evaluate(env: AlfEnvironment, algorithm: RLAlgorithm,
num_episodes: int) -> List[alf.metrics.StepMetric]:
"""Perform one round of evaluation.
Args:
env: the environment
algorithm: the training algorithm
num_episodes: number of episodes to evaluate
Returns:
a... | 37,600 |
async def sample_resource_usage(data_dir: Path, filename: Optional[Union[str, Path]] = None,
measurement_time: Union[int, float] = 10, measurement_cycles: int = 1,
inter_measurement_time: Union[int, float] = 0):
"""Samples resource usage and saves it t... | 37,601 |
def get_plugin_names(blacklist=None, without_backref=False):
"""Return the list of plugins names.
:arg blacklist: name or list of names to not return
:type blacklist: string or list of strings
:arg without_backref: whether or not to include hooks that
have backref "None"
:type without_backr... | 37,602 |
def is_autosync(*args):
"""
is_autosync(name, type) -> bool
is_autosync(name, tif) -> bool
Is the specified idb type automatically synchronized?
@param name (C++: const char *)
@param type (C++: const type_t *)
"""
return _ida_typeinf.is_autosync(*args) | 37,603 |
def scanboards(dirpath):
"""Scans the directory for board files and returns an array"""
print("Scanning for JSON board data files...", end = "")
files = [x for x in subfiles(dirpath) if x.endswith(".json") and not x.endswith("index.json")]
print("Found {} in \"{}\"".format(len(files), dir... | 37,604 |
def router_get_notification() -> dict:
"""Lista todas as configurações do BOT Telegram."""
logger.log('LOG ROTA', "Chamada rota /get_all.")
return {"configuracoes": TelegramNotifier.make_current_cfg_dict()} | 37,605 |
def script_filter_maximum_value(config):
""" The scripting version of `filter_maximum_value`. This
function applies the filter to the entire directory (or single
file). It also adds the tags to the header file of each fits file
indicating the number of pixels filtered for this filter.
Parame... | 37,606 |
def pretty_date(d):
""" returns a html formatted pretty date """
special_suffixs = {1 : "st", 2 : "nd" , 3 : "rd", 21 : "st", 22 : "nd", 23 : "rd", 31 : "st"}
suffix = "th"
if d.tm_mday in special_suffixs:
suffix = special_suffixs[d.tm_mday]
suffix = "<sup>" + suffix + "</sup>"
day = time.strftime("%... | 37,607 |
def update(model, gcs_bucket, gcs_object):
"""Updates the given GCS object with new data from the given model.
Uses last_modified to determine the date to get items from. Bases the
identity of entities in the GCS object on their 'id' field -- existing
entities for which new data is found will be replac... | 37,608 |
def setup_logging(
logger: logging.Logger = logging.getLogger(__name__),
verbose: bool = False,
debug: bool = False,
) -> logging.Logger:
"""Configure logging."""
if debug:
logger.setLevel(logging.DEBUG)
elif verbose:
logger.setLevel(logging.INFO)
else:
logger.setLeve... | 37,609 |
def find_cfsv2_neighbors(input_forcings, config_options, d_current, mpi_config):
"""
Function that will calculate the neighboring CFSv2 global GRIB2 files for a given
forcing output timestep.
:param input_forcings:
:param config_options:
:param d_current:
:param mpi_config:
:return:
... | 37,610 |
def train_protocol():
""" train the model with model.fit() """
model = create_cnn_model(tf_print=True)
model.compile(optimizer='adam', loss='mean_squared_error')
x_all, y_all = load_data_batch(num_images_total=30000)
model.fit(x=x_all, y=y_all, batch_size=128, epochs=50, verbose=1,
... | 37,611 |
def member_requests_list(context, data_dict):
""" Show request access check """
return _only_registered_user() | 37,612 |
def get_conductivity(sw_tdep,mesh,rvec,ham_r,ndegen,avec,fill,temp_max,temp_min,tstep,sw_tau,idelta=1e-3,tau0=100):
"""
this function calculates conductivity at tau==1 from Boltzmann equation in metal
"""
def calc_Kn(eig,veloc,temp,mu,tau):
dfermi=0.25*(1.-np.tanh(0.5*(eig-mu)/temp)**2)/temp
... | 37,613 |
def time_match(
data: List,
times: Union[List[str], List[int], int, str],
conv_codes: List[str],
strptime_attr: str,
name: str,
) -> np.ndarray:
"""
Match times by applying conversion codes to filtering list.
Parameters
----------
data
Input data to perform filtering on
... | 37,614 |
def find_best_input_size(sizes=[40]):
""" Returns the average and variance of the models """
accuracies = []
accuracy = []
t = []
sigma = []
time = []
#sizes = np.arange(5, 80, 5)
for size in sizes:
#for size in [80]:
accuracy = []
N = 20
for j in range(N):
... | 37,615 |
def eval_acc(trainer, dataset="val"):
"""
"""
trainer.model.eval()
with torch.no_grad():
shot_count = 0
total_count = 0
for inputs,targets in trainer.val_dataset():
inputs = nested_to_cuda(inputs, trainer.device)
targets = nested_to_cuda(targets, trainer.d... | 37,616 |
def which(program):
"""
Find a program in PATH and return path
From: http://stackoverflow.com/q/377017/
"""
def is_exe(fpath):
found = os.path.isfile(fpath) and os.access(fpath, os.X_OK)
if not found and sys.platform == 'win32':
fpath = fpath + ".exe"
found = ... | 37,617 |
def _floor(n, base=1):
"""Floor `n` to a multiple of `base`"""
return n // base * base | 37,618 |
def record_pid(ptype: str, running: bool = True) -> int:
"""
记录程序运行的PID
"""
pid = os.getpid() if running else -1
if ptype == 'bpid':
i = dao.update_config([ConfigVO(const.Key.Run.BPID.value, pid)], True)
elif ptype == 'fpid':
i = dao.update_config([ConfigVO(const.Key.Run.FPID.val... | 37,619 |
def fixed_timezone(offset): # type: (int) -> _FixedTimezone
"""
Return a Timezone instance given its offset in seconds.
"""
if offset in _tz_cache:
return _tz_cache[offset]
tz = _FixedTimezone(offset)
_tz_cache[offset] = tz
return tz | 37,620 |
def disable_ntp(sudo_password):
"""List of commands to disable the Network Time Protocol (NTP) Service.
:param str sudo_password: The superuser password to execute commands that require
elevated privileges. The user will be prompted for the password if not supplied
during the call to the run_cli_comman... | 37,621 |
def getFactoriesInfo():
"""
Returns a dictionary with information on how to create an object Sensor from its factory
"""
return {'Stitcher':
{
'factory':'createStitcher'
}
} | 37,622 |
def pending_observations_as_array(
pending_observations: Dict[str, List[ObservationFeatures]],
outcome_names: List[str],
param_names: List[str],
) -> Optional[List[np.ndarray]]:
"""Re-format pending observations.
Args:
pending_observations: List of raw numpy pending observations.
ou... | 37,623 |
def sauv_record_jeu(pseudo, collec, numero, score):
"""
Sauvegarde le nouveau record dans le fichier de record.
:param pseudo: Pseudo du joueur ayant réalisé le nouveau record
:param collec: Collection du puzzle sur lequel il y a eu un nouveau record
:param numero: Numero du puzzle sur lequel... | 37,624 |
def inverted_conditional_planar(input_dim, context_dim, hidden_dims=None):
"""
A helper function to create a
:class:`~pyro.distributions.transforms.ConditionalPlanar` object that takes care
of constructing a dense network with the correct input/output dimensions.
:param input_dim: Dimension of inpu... | 37,625 |
def list_resource_tags(KeyId=None, Limit=None, Marker=None):
"""
Returns a list of all tags for the specified customer master key (CMK).
You cannot perform this operation on a CMK in a different AWS account.
See also: AWS API Documentation
Exceptions
Examples
The following example lists... | 37,626 |
def diagram(data):
"""
Метод строит диаграмму по данным из excel по месяцам за 2017-2019 год.
:param data: Excel данные
:type data: excel
"""
data = data[(data[NAME_DATE] >= pd.Timestamp(year=2017, month=1, day=1)) &
(data[NAME_DATE] <= pd.Timestamp(year=2020, month=12, day=31))... | 37,627 |
def sum_fibonacci():
"""
Find the sum of the even-valued terms of the Fibonacci sequence
"""
fib_sum = 0
n = 1
while fib_sum < 4000000:
if fib(n) % 2 == 0:
fib_sum += fib(n)
n += 1
print(fib_sum) | 37,628 |
def create_category_index(categories):
"""Creates dictionary of COCO compatible categories keyed by category id.
Args:
categories: a list of dicts, each of which has the following keys:
'id': (required) an integer id uniquely identifying this category.
'name': (required) string representing category... | 37,629 |
def n_step_returns(q_values, rewards, kls, discount=0.99):
"""
Calculates all n-step returns.
Args:
q_values (torch.Tensor): the Q-value estimates at each time step [time_steps+1, batch_size, 1]
rewards (torch.Tensor): the rewards at each time step [time_steps, batch_size, 1]
kls (t... | 37,630 |
def user(*args: str) -> str:
"""
Creates an absolute path from the specified relative components within the
user's Cauldron app data folder.
:param args:
Relative components of the path relative to the root package
:return:
The absolute path
"""
return clean(os.path.join('~... | 37,631 |
def widget_search_button_handler(change):
"""The widget_search_button_handler function updates the map when the
Update Search button is selected"""
from erddap_app.layout import (
e,
map,
server,
widget_dsnames,
widget_search_max_time,
widget_search_min_time,
... | 37,632 |
def random_split_exact(iterable, split_fractions=None):
"""Randomly splits items into multiple sample lists according to the given
split fractions.
The number of items in each sample list will be given exactly by the
specified fractions.
Args:
iterable: a finite iterable
split_frac... | 37,633 |
def ordered_partitions(seq, tuples=False):
"""
Generates ordered partitions of elements in `seq`.
Parameters
----------
seq : iterable
Any iterable. Used to generate the partitions.
tuples : bool
If `True`, yields tuple of tuples. Otherwise, yields tuple of
frozensets.
... | 37,634 |
def calc_output_coords(source_dataset, config, model_profile):
"""Construct the coordinates for the dataset containing the extracted variable(s).
The returned coordinates container has the following mapping of attributes to
coordinate names:
* :kbd:`time`: :kbd:`time`
* :kbd:`depth`: :kbd:`depth`
... | 37,635 |
def computeMaskIntra(inputFilename, outputFilename, m=0.2, M=0.9, cc=1):
""" Depreciated, see compute_mask_intra.
"""
print "here we are"
return compute_mask_intra(inputFilename, outputFilename,
m=m, M=M, cc=cc) | 37,636 |
def read_space_delimited(filename, skiprows=None, class_labels=True):
"""Read an space-delimited file
skiprows: list of rows to skip when reading the file.
Note: we can't use automatic comment detection, as
`#` characters are also used as data labels.
class_labels: boolean
if true, the last ... | 37,637 |
def get_gas_price(endpoint=_default_endpoint, timeout=_default_timeout) -> int:
"""
Get network gas price
Parameters
----------
endpoint: :obj:`str`, optional
Endpoint to send request to
timeout: :obj:`int`, optional
Timeout in seconds
Returns
-------
int
Ne... | 37,638 |
def function_3():
"""This is a Function prototype in Python"""
print("Printing Docs String")
return 0 | 37,639 |
def client():
""" client fixture """
return testing.TestClient(app=service.microservice.start_service(), headers=CLIENT_HEADERS) | 37,640 |
def get_character_bullet(index: int) -> str:
"""Takes an index and converts it to a string containing a-z, ie.
0 -> 'a'
1 -> 'b'
.
.
.
27 -> 'aa'
28 -> 'ab'
"""
result = chr(ord('a') + index % 26) # Should be 0-25
if index > 25:
current = index // 26
whi... | 37,641 |
def get_masks_path(base_dir, trial, prune_iter):
"""Builds the mask save path"""
return os.path.join(
base_dir,
"trial_{:02d}".format(trial),
"prune_iter_{:02d}".format(prune_iter),
"masks",
) | 37,642 |
def update_det_cov(
res: OptResult,
jacobian: JacobianValue):
"""Calculates the inv hessian of the deterministic variables
Note that this modifies res.
"""
covars = res.hess_inv
for v, grad in jacobian.items():
for det, jac in grad.items():
cov = propagate_uncert... | 37,643 |
def simplex_init_modified(A, b, c):
"""
Attempt to find a basic feasible vector for the linear program
max: c*x
ST: Ax=b
x>=0,
where A is a (m,n) matrix.
Input Parameters:
A - (n,m) constraint matrix
b - (m,1) vector appearing in the constr... | 37,644 |
def get_all_user_dir():
"""get the root user dir. This is the dir where all users are stored
Returns:
str: path
"""
return os.path.join(get_base_dir(), ALL_USER_DIR_NAME) | 37,645 |
def test_mux_of_mux():
"""Make sure that mux activate still works correctly when a mux
is passed a mux.
"""
a = pescador.Streamer('aaaaaaaaaa')
b = pescador.Streamer('bbbbbbbb')
c = pescador.Streamer('cccccc')
d = pescador.Streamer('dddd')
e = pescador.Streamer('ee')
f = pescador.Str... | 37,646 |
def LeakyRelu(
alpha: float,
do_stabilize: bool = False) -> InternalLayer:
"""Leaky ReLU nonlinearity, i.e. `alpha * min(x, 0) + max(x, 0)`.
Args:
alpha: slope for `x < 0`.
do_stabilize: set to `True` for very deep networks.
Returns:
`(init_fn, apply_fn, kernel_fn)`.
"""
return ABRelu(al... | 37,647 |
def load_interp2d(xz_data_path: str, y: list):
"""
Setup 2D interpolation
Example:
x1, y1, z1, x2, y2, z2\n
1, 3, 5, 1, 4, 6\n
2, 3, 6, 2, 4, 7\n
3, 3 7, 3, 4, 8\n
xy_data_path will lead to a file such as:
1,5,6\n
2,6,7\n
3,7,8\n
y will be: [3, 4]
... | 37,648 |
def save_new_party(json_data):
"""saves a new party in the database
Args:
json_data (json) : party details
Returns:
json : api endpoint response
"""
# Deserialize the data input against the party schema
# check if input values throw validation errors
try:
data = p... | 37,649 |
async def test_availability_poll_state(
hass, mqtt_client_mock, mqtt_mock, setup_tasmota
):
"""Test polling after MQTT connection (re)established."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["if"] = 1
poll_topic = "tasmota_49A3BC/cmnd/STATE"
await help_test_availability_poll_state(
... | 37,650 |
def test_to_compressed_netcdf_for_cdo_no_time_dim_var(air_temperature):
"""Test to_compressed_netcdf if `for_cdo=True` and one var without `time_dim`."""
ds = air_temperature
ds["air_mean"] = ds["air"].isel(time=0)
ds.to_compressed_netcdf("./tmp_testdir/test.nc", for_cdo=True)
os.remove("./tmp_testd... | 37,651 |
def _system_path_separator():
"""
System dependent character for element separation in PATH variable
:rtype: str
"""
if sys.platform == 'win32':
return ';'
else:
return ':' | 37,652 |
def cost_function(theta, X, y, lamda=0.01, regularized=False):
"""
Compute cost and gradient for logistic regression with and without regularization.
Computes the cost of using theta as the parameter for regularized logistic regression
and the gradient of the cost w.r.t. to the parameters.
using l... | 37,653 |
def read_image_numpy(input_filename: Path) -> torch.Tensor:
"""
Read an Numpy file with Torch and return a torch.Tensor.
:param input_filename: Source image file path.
:return: torch.Tensor of shape (C, H, W).
"""
numpy_array = np.load(input_filename)
torch_tensor = torch.from_numpy(numpy_a... | 37,654 |
def init_argparse():
"""Parses the required arguments file name and source database type and returns a parser object"""
parser = argparse.ArgumentParser(
usage="%(prog)s --filename 'test.dtsx' --source 'postgres'",
description="Creates a configuration file in the output directory based on the SQ... | 37,655 |
def solution(n: int = 4000000) -> int:
"""Returns the sum of all fibonacci sequence even elements that are lower
or equals to n.
>>> solution(10)
10
>>> solution(15)
10
>>> solution(2)
2
>>> solution(1)
0
>>> solution(34)
44
"""
fib = [0, 1]
i = 0
while ... | 37,656 |
def mine_biana_info(options):
"""
Generates an interaction network extracting information from BIANA.
"""
# Load config file
scripts_path = os.path.abspath(os.path.dirname(__file__))
config_file = os.path.join(scripts_path, 'config.ini')
config = ConfigParser.ConfigParser()
config.read(c... | 37,657 |
def triu(m: ndarray,
k: int = 0) -> ndarray:
"""
Upper triangle of an array.
"""
af_array = af.data.upper(m._af_array, is_unit_diag=False)
return ndarray(af_array) | 37,658 |
def generate_annotation(overlay_path,img_dim,ext):
"""
Generate custom annotation for one image from its DDSM overlay.
Args:
----------
overlay_path: string
Overlay file path
img_dim: tuple
(img_height,img_width)
ext: string
Image ... | 37,659 |
def _init_weights(m, n: str, head_bias: float = 0.):
""" Mixer weight initialization (trying to match Flax defaults)
"""
if isinstance(m, nn.Linear):
if n.startswith('head'):
nn.init.zeros_(m.weight)
nn.init.constant_(m.bias, head_bias)
else:
nn.init.xavie... | 37,660 |
def parse_episode_page(loc, contents):
"""Parse a page describing a single podcast episode.
@param loc: The URL of this page.
@type loc: basestring
@param contents: The raw HTML contents of the episode page from which
episode information should be parsed.
@type contents: basestring
@ret... | 37,661 |
async def mention_afk(mention):
"""This function takes care of notifying the people who mention you that you are AFK."""
global COUNT_MSG
global USERS
global ISAFK
if mention.message.mentioned and ISAFK:
is_bot = False
if sender := await mention.get_sender():
is_bot = sen... | 37,662 |
def ongoing():
"""
List all active challenges
"""
"""
Invoked by running `evalai challenges ongoing`
"""
display_ongoing_challenge_list() | 37,663 |
def _bitarray_to_message(barr):
"""Decodes a bitarray with length multiple of 5 to a byte message (removing the padded zeros if found)."""
padding_len = len(barr) % 8
if padding_len > 0:
return bitstring.Bits(bin=barr.bin[:-padding_len]).bytes
else:
return barr.bytes | 37,664 |
def join(kmerfile, codonfile, minhashfile, dtemp):
"""Externally join with built-in GNU Coreutils in the order
label, kmers, codons ,minhash
Args:
kmerfile (str): Kmer csv file
codonfile (str): Codon csv file
minhashfile (str): Minhash csv file
dtemp (str): the path to a... | 37,665 |
def extend_with_release_revs(
case_study: CaseStudy, cmap: CommitMap, release_type: ReleaseType,
ignore_blocked: bool, merge_stage: int
) -> None:
"""
Extend a case study with revisions marked as a release. This extender relies
on the project to determine appropriate revisions.
Args:
ca... | 37,666 |
def align_address_to_page(address: int) -> int:
"""Align the address to a page."""
a = align_address(address) >> DEFAULT_PAGE_ALIGN_SHIFT
return a << DEFAULT_PAGE_ALIGN_SHIFT | 37,667 |
def virtual_entities(entity: AnyText, kind: int = Kind.HATCHES) -> EntityQuery:
"""Convert the text content of DXF entities TEXT and ATTRIB into virtual
SPLINE and 3D POLYLINE entities or approximated LWPOLYLINE entities
as outlines, or as HATCH entities as fillings.
Returns the virtual DXF entities as... | 37,668 |
def getNamespace(modelName):
"""Get the name space from rig root
Args:
modelName (str): Rig top node name
Returns:
str: Namespace
"""
if not modelName:
return ""
if len(modelName.split(":")) >= 2:
nameSpace = ":".join(modelName.split(":")[:-1])
else:
... | 37,669 |
def main():
"""Main
"""
logging.basicConfig(level=logging.INFO)
session = ph.HSessionManager.get_or_create_default_session()
#load hda asset and instantiate
hda_asset = ph.HAsset(session, "hda/heightfield_test.hda")
asset_node = hda_asset.instantiate(node_name="HF").cook()
#get node's ... | 37,670 |
def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(
len(environment.comment_start_string),
TOKEN_COMMENT_BEGIN,
e(environment.comment_start_string),
),
(
len(... | 37,671 |
def t_select_scalar_subquery() -> None:
"""scalar subquery should receive the type if first element is a
column only"""
s1 = select(User.id)
s2 = s1.scalar_subquery()
# this should be int but mypy can't see it due to the
# overload that tries to match an entity.
# EXPECTED_TYPE: ScalarSelec... | 37,672 |
def test_network_flow_summary_notebooklet(monkeypatch):
"""Test basic run of notebooklet."""
test_data = str(Path(TEST_DATA_PATH).absolute())
monkeypatch.setattr(data_providers, "GeoLiteLookup", GeoIPLiteMock)
monkeypatch.setattr(data_providers, "TILookup", TILookupMock)
data_providers.init(
... | 37,673 |
def check_env():
"""
fabric.api.env 에 원하는 초기값이 다 들어 있는지 체크
"""
list_of_attributes = [
# remote
'remote_url',
'remote_db_name',
'remote_db_user',
'remote_db_pass',
'remote_wp_path',
'remote_sql_snapshot',
'remote_wp_snapshot',
# loc... | 37,674 |
def monitoring_group(ctx):
"""
Commands for auditing aws environment with awsscripter. This will iclude CISP/ HIPPA Audit for now.
"""
pass | 37,675 |
def test_build_manifest_fail2():
"""Test recursive definition"""
config_file = {'manifest': {
'$BASE': '$TMP/share',
'$TMP': '$BASE/share',
}}
with pytest.raises(Exception):
SonataConfig.from_dict(config_file) | 37,676 |
def get_output(db, output_id):
"""
:param db: a :class:`openquake.server.dbapi.Db` instance
:param output_id: ID of an Output object
:returns: (ds_key, calc_id, dirname)
"""
out = db('SELECT output.*, ds_calc_dir FROM output, job '
'WHERE oq_job_id=job.id AND output.id=?x', output_i... | 37,677 |
def test_subscribe_does_not_exist(db, clients):
"""
Test that a study that does not exist cannot be subscribed to.
"""
client = clients.get("Administrators")
studies = StudyFactory.create_batch(25)
resp = client.post(
"/graphql",
data={"query": SUBSCRIBE_TO, "variables": {"study... | 37,678 |
def compute_window_based_feature(seq,
sample_freq,
func_handle,
window_length,
window_stride,
verbose=False,
**kwargs):
... | 37,679 |
def read_cif(filename):
"""
read the cif, mainly for pyxtal cif output
Be cautious in using it to read other cif files
Args:
filename: path of the structure file
Return:
pyxtal structure
"""
species = []
coords = []
with open(filename, 'r') as f:
lines = f.... | 37,680 |
def custom_data_splits(src_sents, trg_sents, val_samples=3000, seed=SEED):
"""
splits data based on custom number of validation/test samples
:param src_sents: the source sentences
:param trg_sents: the target sentences
:param val_samples: number of validation/test samples
:param seed: the random... | 37,681 |
def normalize(output):
"""将null或者empty转换为暂无输出"""
if not output:
return '暂无'
else:
return output | 37,682 |
def sgd(args):
""" Wrapper of torch.optim.SGD (PyTorch >= 1.0.0).
Implements stochastic gradient descent (optionally with momentum).
"""
args.lr = 0.01 if args.lr == -1 else args.lr
args.weight_decay = 0 if args.weight_decay == -1 else args.weight_decay
args.momentum = 0 if args.momentum == -1 ... | 37,683 |
def normal_conjugates_known_scale_posterior(prior, scale, s, n):
"""Posterior Normal distribution with conjugate prior on the mean.
This model assumes that `n` observations (with sum `s`) come from a
Normal with unknown mean `loc` (described by the Normal `prior`)
and known variance `scale**2`. The "known... | 37,684 |
async def test_fixup(coresys: CoreSys, tmp_path):
"""Test fixup."""
store_execute_reset = FixupStoreExecuteReset(coresys)
test_repo = Path(tmp_path, "test_repo")
assert store_execute_reset.auto
coresys.resolution.suggestions = Suggestion(
SuggestionType.EXECUTE_RESET, ContextType.STORE, re... | 37,685 |
def make_matrix(num_rows, num_cols, entry_fn):
"""retorna a matriz num_rows X num_cols
cuja entrada (i,j)th é entry_fn(i, j)"""
return [[entry_fn(i, j) # dado i, cria uma lista
for j in range(num_cols)] # [entry_fn(i, 0), ... ]
for i in range(num_rows)] | 37,686 |
def add_relationtoforeignsign(request):
"""Add a new relationtoforeignsign instance"""
if request.method == "POST":
form = RelationToForeignSignForm(request.POST)
if form.is_valid():
sourceid = form.cleaned_data['sourceid']
loan = form.cleaned_data['loan']
... | 37,687 |
def check_url(url):
"""
Check if a URL exists without downloading the whole file.
We only check the URL header.
"""
good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]
return get_server_status_code(url) in good_codes | 37,688 |
def table(df, sortable=False, last_row_is_footer=False, col_format=None):
""" generate an HTML table from a pandas data frame
Args:
df (df): pandas DataFrame
col_format (dict): format the column name (key)
using the format string (value)
Return... | 37,689 |
def ap_time_filter(value):
"""
Converts a datetime or string in hh:mm format into AP style.
"""
if isinstance(value, basestring):
value = datetime.strptime(value, '%I:%M')
value_tz = _set_timezone(value)
value_year = value_tz.replace(year=2016)
return value_year.strftime('%-I:%M') | 37,690 |
def set_profile(ctx, param, value):
"""Sets the profile on the global state object when --profile <name> is passed to commands
decorated with @sdk_options."""
if value:
ctx.ensure_object(CLIState).profile = get_profile(value) | 37,691 |
def make_signal(time, amplitude=1, phase=0, period=1):
"""
Make an arbitrary sinusoidal signal with given amplitude, phase and period over a specific time interval.
Parameters
----------
time : np.ndarray
Time series in number of days.
amplitude : float, optional
A specific ampl... | 37,692 |
def commit_release(version: str) -> None:
"""Create a 'Cut <version>' commit and tag."""
commit_message = 'Cut %s' % version
git('add', '.')
git('commit', '-m', commit_message)
git('tag', '-a', '-m', commit_message, version) | 37,693 |
def test_array_to_img_colormap():
"""
Should work as expected
"""
arr = np.random.randint(0, 255, size=(1, 512, 512), dtype=np.uint8)
tileformat = 'png'
utils.array_to_img(arr, tileformat, color_map=utils.get_colormap()) | 37,694 |
def app(test_params, app_params, make_app, shared_result, requests_mock):
"""
Overwrite sphinx.testing.fixtures.app to take the additional fixture requests_mock to fake
intersphinx requests
"""
args, kwargs = app_params
app_ = make_app(*args, **kwargs)
yield app_ | 37,695 |
def on_update_callback(msg_dict):
"""Handler for every JSON message published over the websocket."""
print("GOT message:")
for key, value in list(msg_dict.items()):
if key == 'msg_data':
print('\tmsg_data:')
for data_key, data_value in list(msg_dict['msg_data'].items()):
... | 37,696 |
def print_via_capture():
"""This function prints the values of (a, b, c) to stdout."""
print(ray.get([a, b, c])) | 37,697 |
def train_data(X, y):
"""
:param X: numpy array for date(0-5), school_id
:param y: output for the data provided
:return: return the learned linear regression model
"""
regression = linear_model.LinearRegression()
regression.fit(X, y)
return regression | 37,698 |
def clean_text(s, stemmer, lemmatiser):
"""
Takes a string as input and cleans it by removing non-ascii characters,
lowercasing it, removing stopwords and lemmatising/stemming it
- Input:
* s (string)
* stemmer (object that stems a string)
* lemmatiser (object that lemmatises a s... | 37,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.