content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lastweek_homes_avg():
""" Returns the average of homes we reached last week """
# find last week monday
# iter over tail checking dates
lastweek_monday = date.today() - timedelta(
6 + date.today().isoweekday() % 7)
homes = [0] * 7
for line in Popen(('tail', '-12', settings.DOMICILIOS... | 69,300 |
def lineage(resource):
""" from pyramid.location """
while resource is not None:
yield resource
try:
resource = resource.__parent__
except AttributeError:
resource = None | 69,301 |
def top_k(self, column_name, k, weight_column=None):
"""
Most or least frequent column values.
Parameters
----------
:param column_name: (str) The column whose top (or bottom) K distinct values are to be calculated.
:param k: (int) Number of entries to return (If k is negative, return bottom k... | 69,302 |
def p_read_params(p):
"""read_params : expr_var found_read_param MOAR read_params
| expr_var found_read_param"""
pass | 69,303 |
def connect(server_name, aedt_client_port):
"""Connect to an existing aedt server session.
Parameters
----------
server_name : str
name of the remote machine to connect.
aedt_client_port : int
port on which rpyc_server is running inside AEDT
Returns
-------
rpyc object.... | 69,304 |
def _slice(iterable, pattern):
"""
a custom built slice method that can be used
inside jijna template enginer
:param iterable: string
:param pattern: string ex (::-1)
:return: string
"""
if iterable is None or isinstance(iterable, Undefined):
return iterable
# convert to lis... | 69,305 |
def void_payment(payment_id):
"""Marks the given payment as posted, with the given date."""
transaction = flask.g.db.begin()
try:
# Wipe payment ID from expenses
query = sqlalchemy.text("""
UPDATE budget_expenses
SET payment_id = NULL
WHERE payment_id = (:pi)
""")
# Delete payme... | 69,306 |
def inline_c_precompile(source):
"""Precompile C/C++ code and run it in-line"""
fr = inspect.currentframe().f_back
(lib, code) = _load_func(fr)
return _call_func(lib, code, fr) | 69,307 |
def drop_index():
"""Remove the ALKIS search index"""
a = _get_alkis()
if a:
user, password = clihelpers.database_credentials()
a.drop_index(user, password) | 69,308 |
def docs(node, manifest, config, column_name=None):
"""Return a function that will process `doc()` references in jinja, look
them up in the manifest, and return the appropriate block contents.
"""
current_project = config.project_name
def do_docs(*args):
if len(args) == 1:
doc_p... | 69,309 |
def get_config(path: str) -> EasyDict:
"""Load the configuration file found at ``path``.
Raises:
RuntimeError: when no configuration exists at ``path``.
"""
if not os.path.isfile(path):
raise RuntimeError('cannot locate config at path, %s' % path)
with open(path, 'r') as fp:
... | 69,310 |
def Footer(*content, **attrs):
"""
Wrapper for footer tag
>>> Footer().render()
'<footer></footer>'
"""
return KWElement('footer', *content, **attrs) | 69,311 |
def preprocess_src_dir(dp_config: DatapaneCfg) -> Path:
"""Preprocess source-dir as needed"""
old_mod = dp_config.proj_dir / dp_config.script
# TODO - pass mod_code via classvar in dp_config
if old_mod.suffix == ".ipynb":
log.debug(f"Converting notebook {dp_config.script}")
mod_code = e... | 69,312 |
def dKT(counts, lower_quantile=0.25, upper_quantile=0.75):
"""
Parameters: 1-D array_like, int Vector of counts.
lower_quantile : float, optional
Lower bound of the interquantile range. Defaults to lower quartile.
upper_quantile : float, optional
Upper bound of the interquantile range. Defau... | 69,313 |
def app_validate_batch(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /app-xxxx/validateBatch API method.
For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-validatebatch
"""
fully_qualified... | 69,314 |
def build_dataset(words, vocabulary_size=50000):
"""Returns:
data:
list of the same length as words, with each word replaced by a unique
numeric ID.
count:
counters for the vocabulary_size most common words in 'words'.
dictionary:
maps word->ID
reverse_dictionary:
... | 69,315 |
def cl_args(clgroup):
"""This is a helper function of the function :func:`parse_cmd_arguments` to
add arguments to the continous learning argument group for options specific
to continual learning in a probabilistic setting (with Gaussian posteriors).
Args:
clgroup: The argument group returned b... | 69,316 |
def build_wheel(wheel_directory, config_settings, metadata_directory=None):
"""Invoke the mandatory build_wheel hook.
If a wheel was already built in the
prepare_metadata_for_build_wheel fallback, this
will copy it rather than rebuilding the wheel.
"""
prebuilt_whl = _find_already... | 69,317 |
def check_folder(folder):
"""
Test if folder exists and is absolute
"""
if os.path.isdir(folder):
if os.path.isabs(folder):
return True
else:
raise ValueError("The path to the folder must be absolute")
else:
raise OSError("Can't find the path.") | 69,318 |
def used_voltage_params():
"""
Returns a list of qdac voltage parameters for the used channels
"""
station = qc.Station.default
qdac = station['qdac']
chans = sorted(used_channels())
voltages = [qdac.channels[ii - 1] for ii in chans]
return voltages | 69,319 |
def get_config_files():
"""Get the config file for dataduct
Note:
The order of precedence is:
1. /etc/dataduct.cfg
2. ~/.dataduct/dataduct.cfg
3. DATADUCT_CONFIG_PATH environment variable, if it exists
Returns:
A list of file paths of dataduct config file locations,... | 69,320 |
def make_epoch_log(seconds: float,
metric_data: Dict[str, AverageValueMeter],
epoch: int) -> str:
"""Create the log message basen on input parameters.
Args:
seconds (float): Time spent on train and valid epoch.
metric_data (Dict[str, AverageValueMeter]): Di... | 69,321 |
def _error_matches_criteria(error, criteria):
"""
Check if an error matches a set of criteria.
Args:
error:
The error to check.
criteria:
A list of key value pairs to check for in the error.
Returns:
A boolean indicating if the provided error matches the... | 69,322 |
def eval(device, model, datas, criterion):
"""Eval the model"""
losses = 0
model.eval()
with torch.no_grad():
for data, target in datas:
output = model(data.to(device)).flatten()
losses += criterion(output.flatten(), target.to(device)).item()
return losses / len(datas... | 69,323 |
def find_first_link(content: str) -> Link:
"""Metin içerisindeki ilk bağlantıyı bulur
Arguments:
content {str} -- Metin
Returns:
Link -- Bulunan bağlantı objesi
Examles:
>>> find_first_link('[name1](path1) [name2](path2)')
Link(name='name1', path='path1')
"""
r... | 69,324 |
def create_rfxtrx_tcp_dsmr_reader(host, port, dsmr_version,
telegram_callback, loop=None,
keep_alive_interval=None):
"""Creates a DSMR asyncio protocol coroutine using a RFXtrx TCP connection."""
if not loop:
loop = asyncio.get_event_lo... | 69,325 |
def find_mean_differential_survival(outcomes, interventions):
"""
Given outcomes and interventions, find the maximum restricted mean survival time
"""
from lifelines import KaplanMeierFitter
treated_km = KaplanMeierFitter().fit(outcomes['uncensored time treated'].values, np.ones(len(outcomes)).asty... | 69,326 |
def get_engine(onnx_file_path, engine_file_path=""):
"""Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it."""
def build_engine():
"""Takes an ONNX file and creates a TensorRT engine to run inference with"""
with trt.Builder(TRT_LOGGER) as buil... | 69,327 |
def check_if_git_is_installed():
"""Check if GIT is installed by calling 'git --version'."""
try:
git_version = check_output(["git", "--version"]).decode('utf-8')
if git_version.startswith("git version"):
return True
raise Exception('Git not installed')
except:
re... | 69,328 |
def add_credential(credential: str):
"""
Write creds to .gfi/good-first-issue file if credential argument passed.
Delete config folder if exists and create a new one.
"""
if os.path.exists(credential_dir):
shutil.rmtree(credential_dir)
os.mkdir(credential_dir)
with open(f"{credenti... | 69,329 |
def forward_to_channel(bot: telegram.Bot, chat_id: int, message_id: int, user_id: int) -> None:
"""
Форвардит сообщение в канал музкружка
"""
channel_id = CONFIG.get('muzkruzhok_channel_id', None)
if channel_id is None:
return
if chat_id in CONFIG.get('muzkruzhok_ban_chats', []):
... | 69,330 |
def try_replace_with_core_lstm(op):
"""
Inputs:
op (Operation): op.op_type must be 'tf_lstm_block_cell' or `tf_lstm_block`
Returns:
True if op can be represented by mb.lstm op in SSA. False otherwise
"""
if op.op_type == "tf_lstm_block_cell":
batch = op.x.shape[0]
else: # tf_... | 69,331 |
def pad_punctuation_w_space(text: str) -> str:
"""Pad punctuation marks with space for separate tokenization."""
result = re.sub(r'([:;"*.,!?()/\=-])', r" \1 ", text)
result = re.sub(r"[^a-zA-Z]", " ", result)
result = re.sub(r"\s{2,}", " ", result)
# code for removing single characters
result =... | 69,332 |
def add(ctx, test_case_name, plan, force):
"""
Add a new test case to a plan.
"""
case_dir = os.path.join(*([ctx.obj['ROOT']] + plan.split('.')))
case_file_path = os.path.join(case_dir, test_case_name + '.yml')
if not os.path.exists(case_dir):
os.makedirs(case_dir)
if not force and... | 69,333 |
def get_fastx_flag_extractor(fmt: FastxFormats) -> Type[ABCFlagExtractor]:
"""Retrieves appropriate flag extractor class."""
if FastxFormats.FASTA == fmt:
return FastaFlagExtractor
elif FastxFormats.FASTQ == fmt:
return FastqFlagExtractor
else:
return ABCFlagExtractor | 69,334 |
def mu_post(xs, xs_train, ys_train, kernel, hparams):
"""
Posterior mean conditioned on xs.
Note: a numerical jitter term of 1e-9 is added to avoid nans when inverting
"""
# TODO: use cholesky decomposition for inversion
cov_train = kernels.cov_map(kernel, hparams, xs_train, xs_train) \
... | 69,335 |
def shift_file(file, shift_type='coordinate', x=0, y=0, outfile=None, dtype='default'):
"""
Shift and export raster file in one go
This function can export a shifted version of the input raster file.
Parameters
----------
file : string
Name or path of the fi... | 69,336 |
def tensors2classlist(tensor, seq_lens):
"""
Converts a 3d tensor (max(seq_len), batch_size, output_dim=1) to a 2d class list (list[batch_size * list[seq_len]])
Arguments:
tensor (torch.tensor) : 3d padded tensor of different sequence lengths of
shape (max(seq_lens), batch_size, ou... | 69,337 |
def save_residuals(lightcurve: ndarray, parameters: ndarray, filename: str) -> None:
"""
Save residuals of a light curve to the file.
Parameters
----------
lightcurve : ndarray
An ndarray with (n, 3)-shape storing: time, magnitude, mag's error.
parameters : ndarray
An ndarray w... | 69,338 |
def skippable_exons(exons):
""" Determine which exon(s) can be skipped
For each exon (except the first and second, which cannot be skipped), we
want to find the minimum number of exons which together have a size that
can be divided by 3.
>>> list(skippable_exons([30]))
[]
>>> list(skippable... | 69,339 |
def not_pf(predicate: Callable[[Any], bool]):
"""
Negates the predicate
* **predicate**: predicate to be tested
* **return**: a predicate that is the negation of the passed predicate
>>> p = not_pf(true_p)
>>> p(1)
False
>>> p = not_pf(false_p)
>>> p(1)
True
"""
def i... | 69,340 |
def _ShouldSkip(commit_check, modified_lines, line, rule, test_class=False):
"""Returns whether an error on a given line should be skipped.
Args:
commit_check: Whether Checkstyle is being run on a specific commit.
modified_lines: A list of lines that has been modified.
line: The line that has a rule vi... | 69,341 |
def sharpen_video(source_video, target_video):
"""
Create a movie with a series of frames
frame_name_tag : if your frames are named frame_001.png, frame_name_tag="frame_"
target_video : the video that will be created
"""
import subprocess
import os
command = "ffmpeg -i "+source_video+" -vf unsharp "+target_vi... | 69,342 |
def print_sorted_words(word, metric='cosine'):
"""
Print the words in the vocabulary sorted according to their
embedding-distance to the given word.
Different metrics can be used, e.g. 'cosine' or 'euclidean'.
"""
# Get the token (i.e. integer ID) for the given word.
token = tokenizer.word_... | 69,343 |
def monte_carlo(cycles, precision, concunique, bottom_temp_est, dp, por,
por_fit, seddepths, sedtimes, temp_d, bottom_temp, z,
advection, leg, site, solute_db, ds, por_error, conc_fit,
runtime_errors, line_fit):
"""
Monte Carlo simulation of flux_model output to f... | 69,344 |
def getViewsAlias()->List[str]:
"""获取所有views.py的别名"""
obj = getEnvXmlObj()
return obj.get_childnode_lists('alias/file[name=views]') | 69,345 |
def get_logs(experiment_name: Optional[str] = None, save: bool = False) -> pd.DataFrame:
"""
Returns a table of experiment logs. Only works when ``log_experiment``
is True when initializing the ``setup`` function.
Example
-------
>>> from pycaret.datasets import get_data
>>> jewellery = g... | 69,346 |
def filter_genes(centroids):
"""returns genes that have std > 0"""
return centroids.index[(centroids.std(axis=1) != 0).tolist()] | 69,347 |
def multivariate_t_logpdf(x, m, S, df=np.inf):
"""calculate log pdf for each value
Parameters
----------
x : array_like, shape=(n_samples, n_features)
m : array_like, shape=(n_features,)
S : array_like, shape=(n_features, n_features)
covariance matrix
df : int or float
de... | 69,348 |
def get_iou_score(class_weights=1., smooth=SMOOTH, per_image=True, threshold=None):
"""Change default parameters of IoU/Jaccard score
Args:
class_weights: 1. or list of class weights, len(weights) = C
smooth: value to avoid division by zero
per_image: if ``True``, metric is calculated a... | 69,349 |
def _get_default_wrapper() -> str:
"""Return an available default VISA wrapper as a string ('ivi' or 'py').
Use IVI if the binary is found, else try to use pyvisa-py.
'ni' VISA wrapper is NOT used since version > 1.10.0
and will be removed in 1.12
Raises
------
ValueError
If no ba... | 69,350 |
def scatter(
send_tensor,
recv_tensor,
src,
comm: B.BaguaSingleCommunicatorPy = None,
):
"""Scatters send tensor to all processes associated with the communicator.
Args:
send_tensor (torch.Tensor): Input of the collective, must have a size of ``comm.nranks * recv_tensor.size()`` element... | 69,351 |
def make_flfacts_mach_sweep(alt: float, machs: List[float], eas_limit: float=1000.,
alt_units: str='m',
velocity_units: str='m/s',
density_units: str='kg/m^3',
eas_units: str='m/s') -> Tuple[NDArrayNfloat, ND... | 69,352 |
def get_disease_embeddings_from_existing_models(disease, trained_model_ts):
"""
This function can be used to generate embeddings for a new dataset, using a model that has already been trained.
:param disease: the specific study dataset to be used
:param trained_model_ts: the time stamp of the trained m... | 69,353 |
def create_rnn_numpy_batches(
array, batch_size=500, timesteps=TIMESTEPS, features=1, array_type="X"
):
"""Transform a numpy array, so that it can be fed into an RNN.
RNNs require all batches to be the exact same length. This function
removes excess elements from the array and so ensures all batches ar... | 69,354 |
def nll_loss(input,
label,
weight=None,
ignore_index=-100,
reduction='mean',
name=None):
"""
This api returns negative log likelihood.
See more detail in :ref:`api_nn_loss_NLLLoss` .
Parameters:
input (Tensor): Input tensor, the ... | 69,355 |
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
raise NotImplementedError | 69,356 |
def image_to_string(
image,
lang=None,
config='',
nice=0,
output_type=Output.STRING,
timeout=0,
):
"""
Returns the result of a Tesseract OCR run on the provided image to string
"""
args = [image, 'txt', lang, config, nice, timeout]
return {
Output.BYTES: lambda: run_... | 69,357 |
def organic_pdf_to_img(pdf_file, pdf_dim=None):
"""
Converts pdf file into image
:param pdf_file: path to the pdf file
:return: wand image object
"""
if not pdf_dim:
pdf_dim = get_pdf_dim(pdf_file)
page_width, page_height = pdf_dim
print('read pdf {}'.format(pdf_file))
# img ... | 69,358 |
def test_init_ffn_from_file():
"""Test ffn is created properly from example_bodyplan.csv
"""
from crpm.ffn import FFN
#create FFN from file
model = FFN("crpm/data/example_ffn_bodyplan.csv")
example_bodyplan_assertions(model) | 69,359 |
def correct_bias(in_file, out_file, image_type=sitk.sitkFloat64):
"""
Corrects the bias using ANTs N4BiasFieldCorrection. If this fails, will then attempt to correct bias using SimpleITK
:param in_file: input file path
:param out_file: output file path
:return: file path to the bias corrected image
... | 69,360 |
def download_contest(request, contest_id):
"""Download all submissions of the contest as zip file."""
contest = get_object_or_404(Contest, pk=contest_id)
buffer = io.BytesIO()
zip_archive = zipfile.ZipFile(buffer, mode='w')
for theme in Theme.objects.filter(contest=contest):
# Create empty... | 69,361 |
def list_keys(bucket: str, prefix: str, suffix: str, delta_to: Dict[str, str] = None) -> List[str]:
"""
Lists all the keys belonging to a give key prefix in object storage
:param bucket: The object storage bucket
:param prefix: The key prefix
:param suffix: The key suffix (applied after reading from... | 69,362 |
def arena_sampler(sim_manager):
"""
Generator to randomize all relevant parameters, return an image and the
ground truth labels for the rocks in the image
"""
for i in itertools.count(1):
# Randomize (mod) all relevant parameters
#sim_manager.randomize()
# Grab cam ... | 69,363 |
def info_panel_factory(db):
"""
Returns:
The factory class used to generate info panels for testing.
"""
return InfoPanelFactory | 69,364 |
def brier_score(survival_train, survival_test, estimate, times):
"""Estimate the time-dependent Brier score for right censored data.
The time-dependent Brier score is the mean squared error at time point :math:`t`:
.. math::
\\mathrm{BS}^c(t) = \\frac{1}{n} \\sum_{i=1}^n I(y_i \\leq t \\land \\de... | 69,365 |
def dot(A, B):
"""
Dot product between two arrays.
A -> n_dim = 1
B -> n_dim = 2
"""
arr = []
for i in range(len(B)):
if isinstance(A, dict):
val = sum([v * B[i][k] for k, v in A.items()])
else:
val = sum(map(mul, A, B[i]))
arr.append(val)
... | 69,366 |
def get_invocation_command(toolset, tool, user_provided_command = [],
additional_paths = [], path_last = False):
""" Same as get_invocation_command_nodefault, except that if no tool is found,
returns either the user-provided-command, if present, or the 'tool' parameter.
""... | 69,367 |
def decoding_layer(dec_input, encoder_state,
target_sequence_length, max_target_sequence_length,
rnn_size,
num_layers, target_vocab_to_int, target_vocab_size,
batch_size, keep_prob, decoding_embedding_size):
"""
Create decoding layer
... | 69,368 |
def getGaussianKernel(ksize, sigma, ktype=None):
""" getGaussianKernel(ksize, sigma[, ktype]) -> retval """
pass | 69,369 |
def playSound():
"""
Plays a sound when called (differentiates between Unix and Windows systems). Uncomment to use.
"""
if os.name == "posix":
duration = 0.5 # seconds
freq = 80 # Hz
# os.system('play -nq -t alsa synth {} sine {}'.format(duration, freq))
elif os.name == "nt":
duration = 500 # millisecond... | 69,370 |
def delta():
"""[docstring]"""
pass | 69,371 |
def create_interaction(principal_id, **kw):
"""
Create a new interaction for the given principal ID, make it the
:func:`current interaction
<zope.security.management.newInteraction>`, and return the
:class:`Principal` object.
"""
principal = Principal(principal_id, **kw)
participation = ... | 69,372 |
def python_type(type_description):
"""Return object representing the Python type.
Args:
type_description (str): Arc-style type description/code.
Returns:
Python object representing the type.
"""
instance = {
"date": datetime.datetime,
"double": float,
"singl... | 69,373 |
def openedx_extract_transform_factory(get_config):
"""
Factory for generating OpenEdx extract and transform functions based on the configuration
Args:
get_config (callable): callable to get configuration for the openedx backend
Returns:
OpenEdxExtractTransform: the generated extract an... | 69,374 |
def _mint(challenge, bits):
"""Answer a 'generalized hashcash' challenge'
Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter'
This internal function accepts a generalized prefix 'challenge',
and returns only a suffix that produces the requested SHA leading zeros.
NOTE: Number of ... | 69,375 |
def fast_inspexp_vs(argv):
"""A command line wrapper of compute_fast_inspexp_vs
Parameters
----------
argv: list of str
Command line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, required=True, help="a path to a folder that contains input... | 69,376 |
def product(A, B, p_name):
""" Computes the product automaton of two DFAs.
Args
----
A, B : variables referencing a DFA.
p_name : name of the product automaton.
Returns
-------
An DFA which is a product automaton of input DFA or A and B with name "p_name".
Testable Code
... | 69,377 |
async def magisk(request):
""" magisk latest releases """
url = 'https://raw.githubusercontent.com/topjohnwu/magisk_files/'
releases = '**Latest Magisk Releases:**\n\n'
for type, branch in {"Stable": ["master/stable", "master"], "Beta": ["master/beta", "master"],
"Canary (releas... | 69,378 |
def add_watched_key(key, value, reason, author, authorid, email):
"""
Add key/value combination to key/value tracking list.
Inputs
------
key : str
Key to track; can be wildcard
value : str
Key value to track; can be wildcard
reason : str
Reason to track user
aut... | 69,379 |
def load_data(dataset_str):
"""
Loads input data from gcn/data directory
ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;
ind.dataset_str.al... | 69,380 |
def test_setitem_other_index():
"""
Test if setitem affect other index
"""
M = np.array([2, 3])
T = 5
Mt = Constant_M(M, T)
M_modify = np.array([4, 5])
Mt[1] = M_modify
assert(np.array_equal(Mt[2], np.array([2, 3]))) | 69,381 |
def after_rollback_control(
context: Experiment,
state: List[Run],
configuration: Configuration = None,
secrets: Secrets = None,
**kwargs: Any,
) -> None:
"""
Control run *after* the execution of an Experiments Rollback.
For a given Experiment Rollback and its state, the control creates... | 69,382 |
def dense_video_sampling(videos, annotations=None, bckg_label=201, t_res=16,
t_stride=16, drop_video=True):
"""Sample clips to extract C3D.
Parameters
----------
videos : pandas.DataFrame
Table with info about videos in dataset i.e. unique entry per video.
Requi... | 69,383 |
def dem_quality_check(gdir):
"""Run a simple quality check on the rgitopo DEMs
Parameters
----------
gdir : GlacierDirectory
the glacier directory
Returns
-------
a dict of DEMSOURCE:frac pairs, where frac is the percentage of
valid DEM grid points on the glacier.
"""
... | 69,384 |
def test_particles_db002_particles_db002_v(mode, save_output, output_format):
"""
TEST :3.9.1 The Particle Schema Component [ check length of element
information items ] : The {term} is 'element' with scope=global,
abstract=absent, instant element's namespace is 'targetNamespace'
"""
assert_bind... | 69,385 |
def exec_pip_commands(command):
"""Executes pip command on system
"""
script = []
if create_virtualenv():
activate_cmd = 'call %s' if IS_WINDOWS else 'source %s'
activate_cmd %= FILE_VENV
script.append(activate_cmd)
script.append('echo %s' % command)
script.append(comman... | 69,386 |
def IsImage(a):
"""Return if the object is of Image type.
Args:
a: object whose type needs to be checked
Returns:
True if |a| is of Image type, False otherwise
"""
return isinstance(a, Image) | 69,387 |
def disk_copy(session, dc_ref, src_file, dst_file):
"""Copies the source virtual disk to the destination."""
LOG.debug("Copying virtual disk from %(src)s to %(dst)s.",
{'src': src_file, 'dst': dst_file})
copy_disk_task = session._call_method(
session.vim,
"CopyVirtualDi... | 69,388 |
def upload_to_object_store(
client,
bucket,
full_path_to_filename,
object_name=None,
content_type="binary/octet-stream",
):
"""Uploads the specified file to the object store
Parameters:
client: str, the boto3 client object
bucket: str, target bucket location
full_pat... | 69,389 |
def set_autocommit(autocommit, using=None):
"""Set the autocommit status of the connection."""
return get_connection(using).set_autocommit(autocommit) | 69,390 |
def uninstrument():
"""
Will only prevent new clients from registering tracers.
It's not reasonably feasible to remove existing before/after_request
trace methods of existing clients.
"""
pymongo = utils.get_module('pymongo')
if not utils.is_instrumented(pymongo):
return
utils.r... | 69,391 |
def pull():
""" Description
:raises:
:rtype:
"""
system("git pull") | 69,392 |
def copy_attributes_from_object(in_config, in_object, attr_list):
"""Clones a object and copies attributes from an object to it."""
config = copy.deepcopy(in_config)
for item in attr_list:
if hasattr(in_object, item):
value = getattr(in_object, item)
else:
raise ValueError('attr_list contains ... | 69,393 |
def get_frame_size(*args):
"""get_frame_size(func_t pfn) -> asize_t"""
return _idaapi.get_frame_size(*args) | 69,394 |
def z_decode(p):
"""
调用方式,
while p:
v,p=z_decode(p) #v:值 p:bytes(每次z_decode计算偏移量)
params = v
递归地取字符串p,每次取一些到v,剩下的更新为p,继续迭代
decode php param from string to python 根据php serialize
p: str
"""
#print(p)
if p[0]=='N': #NULL 0x4e-'N'
return None,p[2:]
elif p[0]=='b': #bool 0x62-'b'
if p[2]... | 69,395 |
def scaling_aligned_one_dim_cascade(
time,
x,
y,
z,
track_azimuth,
track_zenith,
):
"""Cascade with topology defined by a cascade at `SCALING_CASCADE_ENERGY`,
and changing energy only modifies number of photons produced"""
return aligned_one_dim_cascade(
time=time,
x=... | 69,396 |
async def test_composite_update(
program: Program,
composite_updated_accounts: tuple[Keypair, Keypair],
) -> None:
"""Test that the call to composite_update worked."""
dummy_a, dummy_b = composite_updated_accounts
dummy_a_account = await program.account["DummyA"].fetch(dummy_a.public_key)
dummy_... | 69,397 |
def test_shape_agg(plot_buildout=False):
"""Test the rev_reeds_plexos pipeline aggregating to plexos nodes
defined by shape."""
plexos_meta, _, profiles = PlexosAggregation.run(
PLEXOS_SHAPES, REV_SC, REEDS_0, CF_FPATH.format(2007),
build_year=2050, plexos_columns=('PCA',),
max_work... | 69,398 |
def GetParsedDeps(deps_file):
"""Returns the full parsed DEPS file dictionary, and merged deps.
Arguments:
deps_file: Path to the .DEPS.git file.
Returns:
An (x,y) tuple. x is a dictionary containing the contents of the DEPS file,
and y is a dictionary containing the result of merging unix and comm... | 69,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.