content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def buy_and_hold_manager_factory(mgr, j:int, y, s:dict, e=1000):
""" Ignores manager preference except every j data points
For this to make any sense, 'y' must be changes in log prices.
For this to be efficient, the manager must respect the "e" convention. That is, the
... | 32,200 |
def explicit_wait_visibility_of_element_located(browser, xpath, timeout=35):
"""Explicitly wait until visibility on element."""
locator = (By.XPATH, xpath)
condition = expected_conditions.visibility_of_element_located(locator)
try:
wait = WebDriverWait(browser, timeout)
result = wait.un... | 32,201 |
def list_all_resources():
"""Return a list of all known resources.
:param start_timestamp: Limits resources by last update time >= this value.
(optional)
:type start_timestamp: ISO date in UTC
:param end_timestamp: Limits resources by last update time < this value.
(optional)
:type ... | 32,202 |
def get_completed_exploration_ids(user_id, collection_id):
"""Returns a list of explorations the user has completed within the context
of the provided collection.
Args:
user_id: str. ID of the given user.
collection_id: str. ID of the collection.
Returns:
list(str). A list of e... | 32,203 |
def test_parallellize_with_args(mocker):
"""Test that parallelize decorator passes arguments to the target function."""
mock = mocker.Mock()
name = mock.__qualname__ = 'mock'
args = 'can dank memes', 'melt steel beams?'
kwargs = dict(tests='pls pass')
parallel_func = parallelize(mock)
paral... | 32,204 |
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
"""
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\?", " ? ", string)
string = re.sub(r"\s{2,}", " ", string)
return string.strip().lower() | 32,205 |
def test_good_cases(task, good_cases):
""" Used to test properly formatted configs. Prints feedback from the task.
Args:
task: A task dictionary mapping 'type' to the task name (e.g. 'ssh')
good_cases: A list of tuples of the form ('configName, config'). config should be properly formatted.
... | 32,206 |
def transitive_closure(graph):
"""
Compute the transitive closure of the graph
:param graph: a graph (list of directed pairs)
:return: the transitive closure of the graph
"""
closure = set(graph)
while True:
new_relations = set((x, w) for x, y in closure for q, w in closure i... | 32,207 |
def call_function(func_name, func_args, params, system):
"""
func_args : list of values (int or string)
return str or None if fail
return ROPChain if success
"""
if( system == Systems.TargetSystem.Linux and curr_arch_type() == ArchType.ARCH_X86 ):
return call_function_linux_x86(func... | 32,208 |
def error_handler(update, context):
"""Log Errors caused by Updates."""
log.error(
'with user: "%s (%s)"\nmessage: "%s"\ntraceback: %s',
update.effective_user,
update.effective_user.id,
context.error,
traceback.format_exc()
)
return ConversationHandler.END | 32,209 |
def jac(w, centred_img_patches, F, NUM_MODES):
"""
The Jacobian of the numerical search procedure.
Parameters
----------
w : numpy array (floats)
Column vector of model weights, used to construct mapping.
centred_img_patches : numpy array (floats)
The mean-centred {p x NUM_PATCH... | 32,210 |
def test_boolean_constraint_deprecated_int():
"""Check that validate_params raise a deprecation message but still passes validation
when using an int for a parameter accepting a boolean.
"""
@validate_params({"param": ["boolean"]})
def f(param):
pass
# True/False and np.bool_(True/Fals... | 32,211 |
def get_session():
"""Entrega uma instancia da session, para manipular o db."""
return Session(engine) | 32,212 |
def activity_horizontal_bar_chart(stock_and_mileage_df: pd.DataFrame.groupby, output_folder):
"""
Horizontal bar chart representing mean activity and other activities per unique categorization
:param stock_and_mileage_df: Dataframe of the vehicles registration list
:param output_folder: output folder ... | 32,213 |
def sdm_ecart(f):
"""
Compute the ecart of ``f``.
This is defined to be the difference of the total degree of `f` and the
total degree of the leading monomial of `f` [SCA, defn 2.3.7].
Invalid if f is zero.
Examples
========
>>> from sympy.polys.distributedmodules import sdm_ecart
... | 32,214 |
async def test_if_fires_on_mqtt_message_with_device(
hass, device_reg, mqtt_mock, tag_mock
):
"""Test tag scanning, with device."""
config = copy.deepcopy(DEFAULT_CONFIG_DEVICE)
async_fire_mqtt_message(hass, "homeassistant/tag/bla1/config", json.dumps(config))
await hass.async_block_till_done()
... | 32,215 |
def draw_gif_frame(image, bbox, frame_no):
"""Draw a rectangle with given bbox info.
Input:
- image: Frame to draw on
- length: Number of info (4 info/box)
- bbox: A list containing rectangles' info to draw -> frame id x y w h
Output: Frame that has been drawn on"""
obj_id = b... | 32,216 |
def build_response(session_attributes, speechlet_response):
""" Build the Alexa response """
# Log
debug_print("build_response")
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} | 32,217 |
def test_raises_correct_count2(
assert_errors,
parse_ast_tree,
context,
first,
second,
third,
default_options,
mode,
):
"""Testing that raises are counted correctly."""
test_instance = context.format(first, second, third)
tree = parse_ast_tree(mode(test_instance))
visito... | 32,218 |
def test_build():
""" Test build of a small filter """
nz = 8 # 128 points equally spaced in theta (z=cos(theta))
nphi = 16 # I usually use nphi=2*nz so regular pixels at equator
# GRF with C_lambda = 1/(1.0 + 10^-4 (lambda(lambda+1))^2)
coeffs = (1.0, 0.0, 1e-4) # this has length scale around l=10 ... | 32,219 |
def modify_branch(sbox, branch, number, conflicting=False):
"""Commit a modification to branch BRANCH. The actual modification depends
on NUMBER. If CONFLICTING=True, the change will be of a kind that
conflicts with any other change that has CONFLICTING=True. We don't
modify (properties on) the branc... | 32,220 |
def create_host(api_client, orig_host_name, orig_host_uid, cloned_host_name, cloned_host_ip):
"""
Create a new host object with 'new_host_name' as its name and 'new_host_ip_address' as its IP-address.
The new host's color and comments will be copied from the the "orig_host" object.
:param api_client: Ap... | 32,221 |
def parenthesize(x):
"""Return a copy of x surrounded by open and close parentheses"""
cast = type(x)
if cast is deque:
return deque(['('] + list(x) + [')'])
return cast('(') + x + cast(')') | 32,222 |
def get_logo_color():
"""Return color of logo used in application main menu.
RGB format (0-255, 0-255, 0-255). Orange applied.
"""
return (255, 128, 0) | 32,223 |
def hello(to_print):
"""
This function prints the paramater
"""
print('Hello ' + to_print) | 32,224 |
def DG(p,t,Ep=10):
"""
Entrenamiento por Descenso de Gradiente
"""
# m será igual al número patrones de
# entrenamiento (ejemplos) y n al número
# de elementos del vector de caracteristicas.
m,n = p.shape
a = 0.5
#--- Pesos iniciales ---
w = np.random.uniform(-0.... | 32,225 |
def batch_name_change():
"""Change the format of pano file name from `rid_order_pid_heading` to `pid_heading`
"""
for fn in tqdm(os.listdir(PANO_FOLFER)):
if 'jpg' not in fn:
continue
old_name = os.path.join(PANO_FOLFER, fn)
new_name = os.path.join(PANO_FOLFER, "... | 32,226 |
def cancel_transfer(transfertool_obj, transfer_id):
"""
Cancel a transfer based on external transfer id.
:param transfertool_obj: Transfertool object to be used for cancellation.
:param transfer_id: External-ID as a 32 character hex string.
"""
record_counter('core.request.cancel_request_... | 32,227 |
def plot_tc_errors(rec, legend=True, ax=None, per_stim=False,
ylim=(0, 200)):
"""
Plot tuning curve (TC) sMAPE.
.. WARNING:: Untested!
.. TODO:: Test or remove `plot_tc_errors`.
Parameters
----------
rec : `.GANRecords`
"""
if ax is None:
_, ax = pyplot.... | 32,228 |
def test_token_authenticator_noauth(app):
"""Create a token for a user relying on Authenticator.authenticate and no auth header"""
name = 'user'
data = {
'auth': {
'username': name,
'password': name,
},
}
r = yield api_request(app, 'users', name, 'tokens',
... | 32,229 |
def delete_video_db(video_id):
"""Delete a video reference from the database."""
connection = connect_db()
connection.cursor().execute('DELETE FROM Content WHERE contentID=%s',
(video_id,))
connection.commit()
close_db(connection)
return True | 32,230 |
def int_to_float_fn(inputs, out_dtype):
"""Create a Numba function that converts integer and boolean ``ndarray``s to floats."""
if any(i.type.numpy_dtype.kind in "ib" for i in inputs):
args_dtype = np.dtype(f"f{out_dtype.itemsize}")
@numba.njit(inline="always")
def inputs_cast(x):
... | 32,231 |
def test_authenticate_password(HTTPConnection):
"""Test rpcpassword/rpcuser authentication"""
destination_address = 'mynHfTyTWyGGB76NBFbfUrTnn8YWQkTJVs'
args = [
'--mnemonic-file={}'.format(datafile('mnemonic_6.txt')),
'--rpcuser=abc',
'--rpcpassword=abc',
'2of3',
'--... | 32,232 |
def _media_item_post_save_handler(*args, sender, instance, created, raw, **kwargs):
"""
A post_save handler for :py:class:`~.MediaItem` which creates blank view and edit permissions
if they don't exist.
"""
# If this is a "raw" update (e.g. from a test fixture) or was not the creation of the item,
... | 32,233 |
def get_sorted_features(available_features: Iterable[Feature] = None):
"""
Register default features and setuptools entrypoint 'ddb_features' inside features registry.
Features are registered in order for their dependency to be registered first with a topological sort.
Withing a command phase, actions a... | 32,234 |
def vel_gradient(**kwargs):
"""
Calculates velocity gradient across surface object in supersonic
flow (from stagnation point) based upon either of two input variable
sets.
First method:
vel_gradient(R_n = Object radius (or equivalent radius, for
shapes that are not axisymmetric),
... | 32,235 |
def lcm(numbers):
""" Get the least common multiple of a list of numbers
------------------------------------------------------------------------------------
input: numbers [1,2,6] list of integers
output: 6 integer """
return reduce(lambda x, y: int((x * y) / gcd(x, y)), numbers, 1) | 32,236 |
def parseBracketed(idxst,pos):
"""parse an identifier in curly brackets.
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (a,b)= parseBracketed(idxst,pos)
... print(st[a:b])
...
>>> test(r'{abc}',0)
{abc}
>>> test(r'{ab8c}',0)
{ab8c... | 32,237 |
def compute_agg_tiv(tiv_df, agg_key, bi_tiv_col, loc_num):
""" compute the agg tiv depending on the agg_key"""
agg_tiv_df = (tiv_df.drop_duplicates(agg_key + [loc_num], keep='first')[list(set(agg_key + ['tiv', 'tiv_sum', bi_tiv_col]))]
.groupby(agg_key, observed=True).sum().reset_index())
if 'is_... | 32,238 |
def convert_configurations_to_array(configs: List[Configuration]) -> np.ndarray:
"""Impute inactive hyperparameters in configurations with their default.
Necessary to apply an EPM to the data.
Parameters
----------
configs : List[Configuration]
List of configuration objects.
Returns
... | 32,239 |
def annual_mean(
start: Optional[datetime] = None,
end: Optional[datetime] = None
) -> dict:
"""Get the annual mean data
----------------------------
Data from March 1958 through April 1974 have been obtained by C. David Keeling
of the Scripps Institution of Oceanography (SIO) and were obtained... | 32,240 |
def test_exit_ok(insights_config, insights_client):
"""
Support collection replaces the normal client run.
"""
with raises(SystemExit) as exc_info:
post_update()
assert exc_info.value.code == 0 | 32,241 |
def exception(logger,extraLog=None):
"""
A decorator that wraps the passed in function and logs
exceptions should one occur
@param logger: The logging object
"""
print logger
def decorator(func):
print "call decorator"
def wrapper(*args, **kwargs):
pri... | 32,242 |
def test_extract_licenses_wrong_file(mocked_function):
"""Test the function extract_licenses()."""
# make sure the LRU cache is clear
get_license_synonyms.cache.clear()
get_license_synonyms()
result = extract_licenses(["this-is-not-a-file"])
assert not result | 32,243 |
def read_external_sources(service_name):
"""
Try to get config from external sources, with the following priority:
1. Credentials file(ibm-credentials.env)
2. Environment variables
3. VCAP Services(Cloud Foundry)
:param service_name: The service name
:return: dict
"""
config = {}
... | 32,244 |
def test_multi_mws_failing_2(client: FlaskClient):
"""test Router.route with multiple middlewares"""
headers = {'content-type': 'application/json'}
resp = client.post('/multi-mws', headers=headers)
assert resp.status_code == 401
assert not resp.json.get('success')
assert resp.json.get('message')... | 32,245 |
def test_validate_custom_integration_manifest(integration: Integration):
"""Test validate custom integration manifest."""
with pytest.raises(vol.Invalid):
integration.manifest["version"] = "lorem_ipsum"
CUSTOM_INTEGRATION_MANIFEST_SCHEMA(integration.manifest)
with pytest.raises(vol.Invalid... | 32,246 |
def intersect(box_a, box_b):
""" We resize both tensors to [A,B,2] without new malloc:
[A,2] -> [A,1,2] -> [A,B,2]
[B,2] -> [1,B,2] -> [A,B,2]
Then we compute the area of intersect between box_a and box_b.
Args:
box_a: (tensor) bounding boxes, Shape: [A,4].
box_b: (tensor) bounding boxes... | 32,247 |
def tokenize(text):
""" tokenize text messages
Input: text messages
Output: list of tokens
"""
# find urls and replace them with 'urlplaceholder'
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
text = re.sub(url_regex, 'urlplaceholder', text)
... | 32,248 |
def peakFindBottom(x, y, peaks, fig=None, verbose=1):
""" Find the left bottom of a detected peak
Args:
x (array): independent variable data
y (array): signal data
peaks (list): list of detected peaks
fig (None or int): if integer, then plot results
verbose (int): verbos... | 32,249 |
def test_parallel_one_process() -> None:
"""
Tests that a `ParallelRunner` runs on a graph with only one process.
"""
runner = ParallelRunner(
graph=MyLocalGraph(
config=MySinkConfig(output_filename=PARALLEL_ONE_PROCESS_FILENAME)
)
)
runner.run()
remaining_numbers... | 32,250 |
def replacelast(string, old, new, count = 1):
"""Replace the last occurances of a string"""
return new.join(string.rsplit(old,count)) | 32,251 |
def parse_config(config):
"""Parse the config dictionary for common objects.
Currently only parses the following:
* `directories` for relative path names.
Args:
config (dict): Config items.
Returns:
dict: Config items but with objects.
"""
# Prepend the base directory ... | 32,252 |
def _safe_read_img(img):
"""
Read in tiff image if a path is given instead of np object.
"""
img = imread(img) if isinstance(img, str) else np.array(img)
return np.nan_to_num(img) | 32,253 |
def max_version(*modules: Module) -> str:
"""Maximum version number of a sequence of modules/version strings
See `get_version` for how version numbers are extracted. They are compared
as `packaging.version.Version` objects.
"""
return str(max(get_version(x) for x in modules)) | 32,254 |
def afire(self):
""" Fire signal asynchronously """
self.logger.debug('Fired %r', self)
for cls in self.__class__.__mro__:
if hasattr(cls, '__handlers__'):
self.logger.debug('Propagate on %r', cls)
for handler in cls.__handlers__:
try:
self... | 32,255 |
def load_secret(name, default=None):
"""Check for and load a secret value mounted by Docker in /run/secrets."""
try:
with open(f"/run/secrets/{name}") as f:
return f.read().strip()
except Exception:
return default | 32,256 |
def snake_case(x):
"""
Converts a string to snake case
"""
# Disclaimer: This method is annoyingly complex, and i'm sure there is a much better way to do this.
# The idea is to iterate through the characters
# in the string, checking for specific cases and handling them accordingly. One note... | 32,257 |
async def process_manga(data_list: list[dict], image_path: str) -> str:
"""对单张图片进行涂白和嵌字的工序
Args:
data_list (list[dict]): ocr识别的文字再次封装
image_path (str): 图片下载的路径(同时也作为最后保存覆盖的路径)
Returns:
str: 保存的路径
"""
image = Image.open(image_path).convert("RGB")
for i in data_list:
... | 32,258 |
def separate(a, start=0, n=None):
"""In-place decimation-in-time: evens->first half, odd->second half
`start` and `n` (length) specify the view into `a`: this function will only modify the
`a[start:start + n]` sub-section of `a`.
"""
n = n or len(a)
b = a[(start + 1):(start + n):2]
a[start:... | 32,259 |
def padded_nd_indices(is_valid, shuffle=False, seed=None):
"""Pads the invalid entries by valid ones and returns the nd_indices.
For example, when we have a batch_size = 1 and list_size = 3. Only the first 2
entries are valid. We have:
```
is_valid = [[True, True, False]]
nd_indices, mask = padded_nd_indic... | 32,260 |
def test_hourlies():
""" BDD Scenario. """ | 32,261 |
def part_two(data: str) -> int:
"""The smallest number leading to an md5 hash with six leading zeros for data."""
return smallest_number_satisfying(data, starts_with_six_zeros) | 32,262 |
def _read_stream(fd, fn):
"""Reads bytes from a file descriptor, utf-8 decodes them, and passes them
to the provided callback function on the next IOLoop tick.
Assumes fd.read will block and should be used in a thread.
"""
while True:
# Specify a max read size so the read doesn't block ... | 32,263 |
def showlatesttag(context, mapping):
"""List of strings. The global tags on the most recent globally
tagged ancestor of this changeset. If no such tags exist, the list
consists of the single string "null".
"""
return showlatesttags(context, mapping, None) | 32,264 |
def cat(file_path, encoding="utf-8", errors="strict"):
"""
.. code:
^-^
(-.-)
|.|
/ \\
| | _/
| || | |
\_||_/_/
:param file_path: Path to file to read
:param encoding: defaults to utf-8 to decode as, will... | 32,265 |
def list_filters():
"""
List all filters
"""
filters = [_serialize_filter(imgfilter) for imgfilter in FILTERS.values()]
return response_list(filters) | 32,266 |
def test_compliant_imei(mocked_imei_data):
"""Tests compliant IMEI"""
compliant_imei_response = mocked_imei_data['compliant']
response = CommonResources.compliance_status(compliant_imei_response, 'basic')
assert "Compliant" in response['compliant']['status'] | 32,267 |
def len_adecuada(palabra, desde, hasta):
"""
(str, int, int) -> str
Valida si la longitud de la palabra está en el rango deseado
>>> len_adecuada('hola', 0, 100)
'La longitud de hola, está entre 0 y 100'
>>> len_adecuada('hola', 1, 2)
'La longitud de hola, no está entre 1 y 2'
:para... | 32,268 |
def test_alpha_path(scale_predictors, fit_intercept, P1):
"""Test regularization path."""
if scale_predictors and not fit_intercept:
return
np.random.seed(1234)
y = np.random.choice([1, 2, 3, 4], size=100)
X = np.random.randn(100, 5) * np.array([1, 5, 10, 25, 100])
model = GeneralizedLi... | 32,269 |
def ECEF_from_ENU(enu, latitude, longitude, altitude):
"""
Calculate ECEF coordinates from local ENU (east, north, up) coordinates.
Args:
enu: numpy array, shape (Npts, 3), with local ENU coordinates
latitude: latitude of center of ENU coordinates in radians
longitude: longitude of ... | 32,270 |
def showresults(options=''):
"""
Generate and plot results from a kima run.
The argument `options` should be a string with the same options as for
the kima-showresults script.
"""
# force correct CLI arguments
args = _parse_args(options)
plots = []
if args.rv:
plots.appe... | 32,271 |
def convert_as_number(symbol: str) -> float:
"""
handle cases:
' ' or '' -> 0
'10.95%' -> 10.95
'$404,691,250' -> 404691250
'$8105.52' -> 8105.52
:param symbol: string
:return: float
"""
result = symbol.strip()
if len(result)... | 32,272 |
def mgus(path):
"""Monoclonal gammapothy data
Natural history of 241 subjects with monoclonal gammapothy of
undetermined significance (MGUS).
mgus: A data frame with 241 observations on the following 12 variables.
id:
subject id
age:
age in years at the detection of MGUS
sex:
`male` or `fema... | 32,273 |
def smiles_dict():
"""Store SMILES for compounds used in test cases here."""
smiles = {
"ATP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C"
+ "@@H](O)[C@H]1O",
"ADP": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)O)[C@@H](O)[C" + "@H]1O",
"meh": "CCC(=O)C(=O)O... | 32,274 |
def prepare_parser() -> ArgumentParser:
"""Create all CLI parsers/subparsers."""
# Handle core parser args
parser = ArgumentParser(
description="Learning (Hopefully) Safe Agents in Gridworlds"
)
handle_parser_args({"core": parser}, "core", core_parser_configs)
# Handle environment subpa... | 32,275 |
def import_google(authsub_token, user):
"""
Uses the given AuthSub token to retrieve Google Contacts and
import the entries with an email address into the contacts of the
given user.
Returns a tuple of (number imported, total number of entries).
"""
contacts_service = gdata.contact... | 32,276 |
def level_6(nothing_value):
"""Given a starting value for the 'nothing' value, follow the chain."""
filename = nothing_value + '.txt'
comments = []
with zipfile.ZipFile(ZIPFILE) as zip:
while True:
print(" [*] Contents of {}:".format(filename))
with zip.open(... | 32,277 |
def getGpsTime(dt):
"""_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime
"""
total = 0
days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc.
total += days*3600*24
total += dt.hour * 3600
total += dt.minute * 60
total += dt.second
return(total) | 32,278 |
def class_logger(module_logger, attribute = "logger"):
"""
Class decorator to add a class-level Logger object as a class
attribute. This allows control of debugging messages at the class
level rather than just the module level.
This decorator takes the module logger as an argument.
"""
def decorator(cl... | 32,279 |
def validate_date(date, flash_errors=True):
"""
Validates date string. Format should be YYYY-MM-DD. Flashes errors if
flash_errors is True.
"""
try:
datetime.datetime.strptime(date, '%Y-%m-%d')
except ValueError:
if flash_errors:
flask.flash('Invalid date provided. Make sure dates are in YYYY-... | 32,280 |
def makeImg(qr: object, filename: str) -> None:
""" Convert the qr code into '*.png' format and save in under 'qr_img' """
mat = _magnify(qr.get_qr_matrix_with_margins())
img = Image.fromarray((mat*255).astype(np.uint8), 'L')
_saveImg(img, filename) | 32,281 |
def generate_error_map(image, losses, box_lenght):
"""
Function to overlap an error map to an image
Args:
image: input image
losses: list of losses, one for each masked part of the flow.
Returs:
error_map: overlapped error_heatmap and image.
"""
box_lenght = int(box_lengh... | 32,282 |
def get_order(oid): # noqa: E501
"""Gets an existing order by order id
# noqa: E501
:param oid:
:type oid: str
:rtype: Order
"""
oid = int(oid)
msg = "error retrieving order"
ret_code = 400
if oid in orders:
msg = {"status": f"order retrieved", "order": orders[oid],... | 32,283 |
def remove_page(page_id):
"""Remove a page from the list of pages to be scraped"""
if isfile(PAGES_F_PATH) and getsize(PAGES_F_PATH) != 0:
with open(PAGES_F_PATH, 'r+') as pages_file:
try:
pages = json.load(pages_file)
for page in pages:
i... | 32,284 |
def run_with_lightning(model, data_loader,
experiment: str,
hp: Params,
gpus: int, cpus: int,
max_epochs: int,
best_model_callback,
out_data: List,
run=1, moni... | 32,285 |
def delete_object(client, args):
"""
Removes a file from a bucket
"""
parser = argparse.ArgumentParser(PLUGIN_BASE+' del')
parser.add_argument('bucket', metavar='BUCKET', type=str,
help="The bucket to delete from.")
parser.add_argument('file', metavar='OBJECT', type=str,... | 32,286 |
def test_atomic_integer_enumeration_nistxml_sv_iv_atomic_integer_enumeration_1_2(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema-SV-IV-atomic-integer-enumeration-1.xsd",... | 32,287 |
def most_recent_assembly(assembly_list):
"""Based on assembly summaries find the one submitted the most recently"""
if assembly_list:
return sorted(assembly_list, key=operator.itemgetter('submissiondate'))[-1] | 32,288 |
def dict_from_xml_text(xml_text, fix_ampersands=False):
"""
Convert an xml string to a dictionary of values
:param xml_text: valid xml string
:param fix_ampersands: additionally replace & to & encoded value before parsing to etree
:return: dictionary of data
"""
if fix_ampersands:
... | 32,289 |
def find_encryption_key(loop_size, subject_number):
"""Find encryption key from the subject_number and loop_size."""
value = 1
for _ in range(loop_size):
value = transform_value(value, subject_number)
return value | 32,290 |
def test_status_string():
"""status_string should be the string version of the status code."""
assert gx.GrpcException().status_string == "UNKNOWN"
assert (
gx.GrpcException(status_code=grpc.StatusCode.NOT_FOUND).status_string
== "NOT_FOUND"
)
assert gx.NotFound().status_string == "N... | 32,291 |
def carla_rotation_to_RPY(carla_rotation):
"""
Convert a carla rotation to a roll, pitch, yaw tuple
Considers the conversion from left-handed system (unreal) to right-handed
system (ROS).
Considers the conversion from degrees (carla) to radians (ROS).
:param carla_rotation: the carla rotation
... | 32,292 |
def compute_p1_curl_transformation(space, quadrature_order):
"""
Compute the transformation of P1 space coefficients to surface curl values.
Returns two lists, curl_transforms and curl_transforms_transpose. The jth matrix
in curl_transforms is the map from P1 function space coefficients (or extended sp... | 32,293 |
def _get_individual_id(individual) -> str:
"""
Returns a unique identifier as string for the given individual.
:param individual: The individual to get the ID for.
:return: A string representing the ID.
"""
if hasattr(individual, "identifier") and (isinstance(individual.identifier, list) and
... | 32,294 |
def collate(root, collators=DEFAULT_COLLATORS):
"""
ScrollNode collator. Modifies tree in place.
Takes two arguments, a root node, and a dict of collation functions.
Each key in this dict is a node kind,
and each value is a string, function pair.
The string being the joining string (see str.join... | 32,295 |
def get_self_url(d):
"""Returns the URL of a Stash resource"""
return d.html_url if isinstance(d, PullRequest) else d["links"]["self"][0]["href"] | 32,296 |
def shift(arr, *args):
"""
**WARNING**
The ``Si`` arguments can be either a single array containing the shift
parameters for each dimension, or a sequence of up to eight scalar shift
values. For arrays of more than one dimension, the parameter ``Sn`` specifies
the shift applied to the n-th dime... | 32,297 |
def ConvertToMeaningfulConstant(pset):
""" Gets the flux constant, and quotes it above some energy minimum Emin """
# Units: IF TOBS were in yr, it would be smaller, and raw const greater.
# also converts per Mpcs into per Gpc3
units=1e9*365.25
const = (10**pset[7])*units # to cubic Gpc an... | 32,298 |
def stop_child_processes() -> NoReturn:
"""Stops sub processes (for meetings and events) triggered by child processes."""
with db.connection:
cursor_ = db.connection.cursor()
children = cursor_.execute("SELECT meetings, events FROM children").fetchone()
for pid in children:
if not pi... | 32,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.