content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def multi_check_output(cmd_lst, stderr=None, env=None, num_retry=NUM_RETRY):
""" This routine should always return a (unicode) string.
NOTE: Under python3, sp.check_output returns bytes by default, so we
set universal_newlines=True to guarantee strings.
"""
itry, cmd_retry = 1, True
out_str = No... | 5,288,000 |
def check_unit_axis_sums(a, whom, axis=0):
"""Check sum along array axis is close to one."""
axis_sums = a.sum(axis=axis)
if not np.all(np.isclose(axis_sums, 1)):
raise ValueError(
'Array with incorrect axis sums passed to %s. '
'Expected sums along axis %d to be 1.'
... | 5,288,001 |
async def github_get_pr_reviews(client_session, owner, repo, pr_number):
"""
Get the reviews of a given pull-request.
Args:
client_session: aiohttp ClientSession.
owner: owner of the repository at github.
repo: repository name at github (without owner part).
pr_number (int):... | 5,288,002 |
def read_array_objects(container, size, items, dkey, akey, obj):
"""Read data from the container.
Args:
container (DaosContainer): the container from which to read objects
size (int): number of arrays to read
items (int): number of items in each array to read
dkey (str): dkey us... | 5,288,003 |
def get_nth_digit(N, n):
"""
return the nth digit from an N digit number
>>> get_nth_digit(12345, 3)
4
>>> get_nth_digit(12345, 7)
Traceback (most recent call last):
...
IndexError: string index out of range
"""
return int(str(N)[n]) | 5,288,004 |
def check_device() -> str:
"""Check if there is an available remote
:return: The name of the device
"""
cmd = adb_command_handler('devices').strip().split('\n')
devices = []
device = ''
del cmd[0]
for line in cmd:
if 'device' not in line:
continue
device = li... | 5,288,005 |
def prints_ofp(msg):
"""
Args:
msg: OpenFlow 1.3 message unpacked by python-openflow
Returns:
"""
try:
msg_types = {0: print_ofpt_hello, # ok
1: print_ofpt_error, # ok
2: print_ofpt_echo_request, # ok
3: print_ofpt_ec... | 5,288,006 |
def stereoCameraViewCallback(*args):
"""
Main callback point for sending information to the editor command.
The format of the callback is as follows:
arg1 = the name of the editor
arg2 = keyword dictionary represented as a string.
"""
pass | 5,288,007 |
def split_path(filepath):
"""Return filename and extension of file"""
return os.path.splitext(filepath) | 5,288,008 |
def generate_tmp_file_path(
tmpdir_factory, file_name_with_extension: str, tmp_dir_path: Optional[Path] = None
) -> Path:
"""Generate file path relative to a temporary directory.
:param tmpdir_factory: py.test's `tmpdir_factory` fixture.
:param file_name_with_extension: file name with extension e.g. `f... | 5,288,009 |
def check_params(params, C, max_len):
"""Check for validity of parameters"""
if (C<=0):
sys.stderr.write( "\nerror: the parameter 'C' has to be larger than 0\n" )
assert(C>0)
if params.has_key("degree"):
if (params["degree"]<=0):
sys.stderr.write( "\nerror: the parameter... | 5,288,010 |
def unitTest():
"""A simple unit test for the am_ribbon command"""
curve = cmds.curve(d=3,
p=[[-3,0,-5],
[-2.75,0,-3.916667],
[-2.25,0,-1.75],
[0,0,0],
[2.25,0,1.75],
[2.75,0,3.916667],
[3,0,5]],
k=[0,0,0,1,2,3,4,4,4])
# test create mode
print '---TESTING CREATE---'
ribbon = cmds.am_ribbo... | 5,288,011 |
def _add_bitbake_layers(workdir):
"""
Add the necessary bitbake layers.
Args:
* workdir (Path): top level of work area.
"""
command = [
str(SCRIPTS_DIR / "poky-bitbake-wrapper.sh"),
str(workdir),
"bitbake-layers",
"add-layer",
]
layers = [
"meta... | 5,288,012 |
def mul_param(arr_t, param_dtype):
"""
Returns a scaling transformation with a dynamic parameter (1 output, 1 input, 1 scalar):
``output = input * param``.
"""
return Transformation(
[Parameter('output', Annotation(arr_t, 'o')),
Parameter('input', Annotation(arr_t, 'i')),
Par... | 5,288,013 |
def plotApprox3D(kernel, parameter, lD, uD, name=None):
"""Draws a 2-dimensional kernel summation function of the form
in between the squared domain from lD to uD
Parameters
----------
kernel : IKernelBase
object that implements the IKernelBase interface
parameter : numpy array
... | 5,288,014 |
def send_email_verify(user, request, changed_email=None):
"""
Sending email with link to verify user
"""
user = get_object_or_404(get_user_model(), email=user.email)
token = RefreshToken.for_user(user).access_token
current_site = get_current_site(request).domain
relative_link = reverse('use... | 5,288,015 |
def GetDateAndTime():
"""Obtain date and time."""
return datetime.datetime.utcnow().isoformat() + "Z" | 5,288,016 |
def python_as_first_skill():
"""
>>> SELECT * WHERE UPPER(member.skills[1]::text) = UPPER('Python')
"""
member_list = Member.objects.filter(skills__0__iexact="Python")
for member in member_list:
skills = ', '.join(member.skills)
print("{0} loves python : {1}".format(member, skills)) | 5,288,017 |
def get_columns_by_variance(X, y, threshold=0.0):
"""
Method to fetch columns based on threshold variance
"""
from sklearn.feature_selection import VarianceThreshold
selector = VarianceThreshold(threshold).fit(X, y)
return X.columns[selector.get_support()] | 5,288,018 |
def split_outputs_per_head(outputs: Tuple[NDArray], heads: list) -> List[List[NDArray]]:
"""
Split outputs into outputs per head
:param outputs: list of all outputs
:param heads: list of all heads
:return: list of outputs for each head
"""
head_outputs = []
for h in heads:
head_o... | 5,288,019 |
def get_neighbors(glycan, glycans, libr = None, graphs = None):
"""find (observed) biosynthetic precursors of a glycan\n
| Arguments:
| :-
| glycan (string): glycan in IUPAC-condensed format
| glycans (list): list of glycans in IUPAC-condensed format
| libr (list): library of monosaccharides; if you have on... | 5,288,020 |
def cli(examples, output_file=None, title=None):
"""Generate a notebook from a list of example functions.
EXAMPLES are expected to be a list of files and the functions located
within those files, for example, to inline the 'reserve_node' function
located in 'tests/test_lease.py':
generate_notebo... | 5,288,021 |
def test_int_asc(get_good_response, structures):
"""Ascending sort (integer)"""
limit = 5
request = f"/structures?sort=nelements&page_limit={limit}"
data = structures.collection.find(sort=[("nelements", 1)], limit=limit)
expected_nelements = [_["nelements"] for _ in data]
response = get_good_r... | 5,288,022 |
def do_service_enable(cs, args):
"""Enable the service."""
result = cs.services.enable(args.service_id)
utils.print_list([result], ["Id", "Binary", "Host", "Status", "State",
"Updated_at", "Disabled Reason"]) | 5,288,023 |
def get_saliency_from_feat_list(feat_list, model, device,
got_tensors=True,
sal_type=1):
"""
Given a features list from one instance, get saliencies of this instance.
Return list of saliencies.
n_class
feat_list:
Feature list of ten... | 5,288,024 |
def k8s_get_credentials(name, resource_group_name,
path=os.path.join(os.path.expanduser('~'), '.kube', 'config'),
ssh_key_file=None):
"""Download and install kubectl credentials from the cluster master
:param name: The name of the cluster.
:type name: str
... | 5,288,025 |
def decompress_article_set(file_path: str, output_file: str):
"""Unzip articles sets and create xml file."""
with gzip.open(file_path, 'rb') as f_in:
with open(output_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out) | 5,288,026 |
def vjp_maker_solve_Hz_source(Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER):
""" Gives vjp for solve_Hz with respect to source """
A = make_A_Hz(info_dict, eps_vec)
def vjp(v):
return 1j * info_dict['omega'] * sparse_solve(A.T, v, iterative=iterative, method=method)
... | 5,288,027 |
def _update_state_dict_according_to_operation(state_dict, operation, qubit_indexes,
merge_strings=None):
"""
Updates the keys of the state_dict according to the operation being applied to the circuit
Args:
state_dict: A dictionary wi... | 5,288,028 |
def run_cmd(command, verbose=True, shell='/bin/bash'):
"""internal helper function to run shell commands and get output"""
process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell)
output = process.stdout.read().decode().strip().split('\n')
if verbose:
# return full outp... | 5,288,029 |
def test_add_payload():
"""
Test add_payload method in modify_jwt.py
"""
with pytest.raises(InvalidJwtJson):
add_payload({}, {})
with pytest.raises(InvalidParam):
add_payload(jwt_json, "")
new_jwt_json = add_payload(jwt_json, add_payload_value)
assert list(new_jwt_json[PAYL... | 5,288,030 |
def main():
"""
main()
:return:
"""
urls = get_urls(url)
keywords = get_keywords(url)
urls_keywords = get_urls_keywords(urls, keywords)
urls_keywords_thread = get_urls_keywords_thread(urls, keywords)
urls_keywords_thread_rich = get_urls_keywords_thread_rich(urls, keywords)
print(... | 5,288,031 |
def test_documentation_example():
"""Test basic code example shown in documentation"""
from imblearn.datasets import fetch_datasets
datasets = fetch_datasets(filter_data=['oil'])
X, y = datasets['oil']['data'], datasets['oil']['target']
labels, counts = np.unique(y, return_counts=True)
assert ... | 5,288,032 |
def _strip_version(version):
"""Strip trailing characters that aren't digits or '.' from version names.
Some OS versions look like "9.0gm", which is not useful for select()
statements. Thus, we strip the trailing "gm" part.
Args:
version: the version string
Returns:
The version with trailing letter... | 5,288,033 |
def set_constraint_production(input_file, model):
"""
Set constraints on uptake and min growth rate
Given the input file and the model it constraints uptake
and min growth rate:
1) uptake:
- if the user has chosen a value for the lb of the carbon source
it sets the selected one
... | 5,288,034 |
def list_from_env(key, default=""):
"""
Splits a string in the format "a,b,c,d,e,f" into
['a', 'b', 'c', 'd', 'e', 'f', ]
"""
try:
val = os.environ.get(key, default)
return val.split(',')
except (KeyError, ValueError):
return [] | 5,288,035 |
def server(
credentials_file,
credentials_blob,
bind,
port,
tls_certificate,
token,
max_line_size,
recv_size,
cleanup_timeout,
queued_events,
batch_size,
batch_timeout,
retry_max_attempts,
retry_max_wait,
retry_multiplier,
api_timeout,
api_max_connecti... | 5,288,036 |
def calculate_head_direction_from_leds(positions, return_as_deg=False):
"""
Calculates head direction based on X and Y coordinates with two LEDs.
Parameters
----------
positions : (N, 2) array_like
N samples of observations, containing X and Y coordinates
return_as_deg : bool
R... | 5,288,037 |
def GridGraph(dim_list):
"""
Returns an n-dimensional grid graph.
INPUT:
- ``dim_list`` - a list of integers representing the
number of nodes to extend in each dimension.
PLOTTING: When plotting, this graph will use the default
spring-layout algorithm, unless a position dictionary i... | 5,288,038 |
def calculate_turn(state: str):
"""
Calculates which player's turn it is given board state.
"""
num_black = 0
num_white = 0
for cell in state:
if cell in cellState.black_pieces:
num_black += 1
elif cell in cellState.white_pieces:
num_white += 1
return ... | 5,288,039 |
def set_token_in_cookie(res):
"""Cookieへのトークンの保存
一度送られてOKだったトークン情報はCookieに入れてブラウザからのアクセスに対応する。
"""
if request.endpoint == 'login':
return res
token = read_token()
if token:
max_age = 60 * 60 * 24 * 1
expires = int(datetime.now().timestamp()) + max_age
res.set_coo... | 5,288,040 |
def load_global_covid_data():
"""
Load global COVID-19 data from JHU.
"""
# Login to ArcGIS
arcconnection = BaseHook.get_connection("arcgis")
arcuser = arcconnection.login
arcpassword = arcconnection.password
gis = GIS("http://lahub.maps.arcgis.com", username=arcuser, password=arcpasswor... | 5,288,041 |
def PrayerTimes(method=CalculationMethod.MWL, asr=AsrMethod.STANDARD) -> GeneralMethod:
"""Generates an object that can be used to generate prayer times.
Args:
method (CalculationMethod): Method to use for general calculations.
Defaults to CalculationMethod.MWL.
asr (AsrMethod): Met... | 5,288,042 |
def is_header_file(filename):
"""Return True if "filename" is a header file.
>>> is_header_file('foo.c')
False
>>> is_header_file('foo.h')
True
>>> is_header_file('foo.h++')
True
"""
extension = os.path.splitext(filename)[1]
return extension.lower() in HEADER_EXTENSIONS | 5,288,043 |
def channel_histograms(df, xlim=None, n_bins=100, save_fig_filename=None):
"""Make histograms for each column.
Parameters
--------
df : pandas.DataFrame
a table of cells by channel names.
"""
sns.set(font_scale=3)
plt.rcParams['patch.linewidth'] = 0
plt.rcParams['patch.edgecolo... | 5,288,044 |
def change_vpsa_cache(session, vpsa_id, quantity, return_type=None, **kwargs):
"""
Sets the quantity of additional cache groups for a VPSA. The quantity of
cache groups that comes with the base engine is not included in this
calculation. For example, if the engine comes with 2 cache groups,
passin... | 5,288,045 |
def parse_radius(radius):
"""
Method for parsing min/max radius argument
:param radius: point radius
:type: str, numeric, or None
:returns: min or max radius
:type: float or None
"""
err_msg = "Invalid radius: (%s) must be a positive float." % (radius)
radius = str_to_float(radius, e... | 5,288,046 |
def export_package():
"""Export package as JSON."""
package_doc = frappe.get_single("Package Publish Tool")
package = []
for doctype in package_doc.package_details:
filters = []
if doctype.get("filters_json"):
filters = json.loads(doctype.get("filters_json"))
docs = frappe.get_all(doctype.get("document_... | 5,288,047 |
def build_docker(image):
"""Build a Docker image."""
_, dockerfile, _ = docker_paths(image)
utils.run.run(
[
"docker",
"build",
"-f",
dockerfile,
"-t",
"singlecellopenproblems/{}".format(image),
BASEDIR,
],
... | 5,288,048 |
def test_typical_workflow(s3_fixture): # noqa: F811
"""
Tests all methods of the ObjectStorageS3 DAO implementation in one long workflow.
"""
object_fixture = s3_fixture.non_existing_objects[0]
typical_workflow(
storage_client=s3_fixture.storage,
bucket1_id=s3_fixture.non_existing_b... | 5,288,049 |
def station_reindex(stations: List[dict]) -> List[dict]:
"""
reindexes the opnnem formatted facilities from a list
to a dict keyed by duid
"""
stations_return = {}
for station_code, station in stations.items():
facs = []
if "facilities" in station:
facs = s... | 5,288,050 |
def load_jcmod(eid, params):
"""
Basically trying to dynamically load the correct job controller
(perform a 'from typejobcontroller import TypeJobController')
"""
# build with a known naming convention
module_name = params['run']['scheduler'] + "jobcontroller"
class_name_cc = param... | 5,288,051 |
def test_null_agencies_accounts(client, monkeypatch, basic_idvs):
"""
We are going to null out some accounts/agencies to ensure our count is
correct. According the LOVELY drawing in idv_test_data.py, C14 will
be a great candidate for this exercise. It's ultimate parent is I2.
"""
# Grab the co... | 5,288,052 |
def config_entry_fixture(hass, config):
"""Define a config entry fixture."""
entry = MockConfigEntry(domain=DOMAIN, data=config)
entry.add_to_hass(hass)
return entry | 5,288,053 |
def processDBRelease(inputFiles, inFilesGuids, realDatasetsIn, dispatchDblock, dispatchDBlockToken, prodDBlockToken, workdir, jobPars):
""" remove any DBRelease files from the input file list and send back instruction to move the created DBRelease file to job dir """
_inputFiles = inputFiles
_inFilesGuids ... | 5,288,054 |
def radar_analysis_status_command(client: PolarisClient, args: Dict[str, Any]):
"""
Check the Radar Event for updates.
:type client: ``PolarisClient``
:param client: Rubrik Polaris client to use
:type args: ``dict``
:param args: arguments obtained from demisto.args()
:return: CommandResul... | 5,288,055 |
def create_vote(user_id: str) -> FlexSendMessage:
"""投票創建確認
Args:
user_id (str): 使用者 ID
Returns:
FlexSendMessage: 投票創建確認
"""
with open("line/model/create_vote.json") as json_file:
contents = json.load(json_file)
contents["footer"]["contents"][0]["action"][
"uri"... | 5,288,056 |
def build_automata(engine, A):
"""
building automata should be single threat
Automata in general are not threat safe structure
"""
print("Building automata")
session = Session(engine)
for each_row in session.query(Entities_dict).all():
A.add_word(each_row.syn_term, (each_row.concept_... | 5,288,057 |
def join_csv():
"""
Helper function to join the results of various csv.
"""
# Initialize csv container
csv = []
# Get all csv
for item in os.listdir():
if item.endswith('.csv'):
csv.append(item)
# Comprehension to come
frame = pd.concat((pd.read_csv(item) for item... | 5,288,058 |
def followRedirects(categories):
"""If a category is a redirect, replace the category with the target."""
result = []
for cat in categories:
categoryPage = pywikibot.Page(pywikibot.Site(u'commons', u'commons'),
cat, ns=14)
if categoryPage.isCategoryRedir... | 5,288,059 |
def ncdf(x):
"""Cumulative normal dist'n."""
global rt2
return 1.0 - 0.5*erfcc(x/rt2) | 5,288,060 |
def test_ap_wpa2_in_different_bridge(dev, apdev):
"""hostapd behavior with interface in different bridge"""
ifname = apdev[0]['ifname']
br_ifname = 'ext-ap-br0'
try:
ssid = "test-wpa2-psk"
passphrase = "12345678"
hostapd.cmd_execute(apdev[0], ['brctl', 'addbr', br_ifname])
... | 5,288,061 |
def patch_input(**kwargs):
"""A helper to provide mocked cm patching input function which was renamed in PY3"""
return patch.object(builtins, 'input', **kwargs) | 5,288,062 |
def hash_1():
""" Test hash 1"""
return "73bef2ac39be261ae9a06076302c1d0af982e0560e88ac168980fab6ea5dd9c4" | 5,288,063 |
def cli(ctx, atlas_base_url, atlas_api_username,
atlas_api_password, http_timeout, log_level):
"""
Astrolabe is a command-line application for running automated driver
tests against a MongoDB Atlas cluster undergoing maintenance.
"""
client = AtlasClient(
base_url=atlas_base_url,
... | 5,288,064 |
def is_sequence(obj) -> bool:
"""
Return True if obj is a generic sequence type, like a list or tuple.
"""
return isinstance(obj, (list, tuple, set, DictKeySet, DictValueSet)) | 5,288,065 |
def adjust_learning_rate(optimizer, epoch, lr, epochs_for_decay):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
new_lr = lr * (0.1 ** (epoch // epochs_for_decay))
print('Changing learning rate in ', new_lr)
for param_group in optimizer.param_groups:
param_group['lr... | 5,288,066 |
def _RGB2sRGB(RGB):
"""
Convert the 24-bits Adobe RGB color to the standard RGB color defined
in Web Content Accessibility Guidelines (WCAG) 2.0
see https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef for more references
:param RGB: The input RGB color or colors shape== ... x 3 (R,... | 5,288,067 |
def go(arg):
"""
Creates and trains a basic transformer for the IMDB sentiment classification task.
"""
tbw = SummaryWriter(log_dir=arg.tb_dir) # Tensorboard logging
# load the IMDB data
if arg.final:
train, test = datasets.IMDB.splits(TEXT, LABEL)
TEXT.build_vocab(train, max_s... | 5,288,068 |
def find_meeting_point(river_1, river_2):
"""
Find the first meeting point of two rivers
"""
meeting_points = []
while not meeting_points:
points_1 = []
points_2 = []
for _ in range(10000):
points_1.append(next(river_1))
points_2.append(next(river_2))
... | 5,288,069 |
def _is_physical_entity(pe):
"""Return True if the element is a physical entity"""
val = isinstance(pe, _bp('PhysicalEntity')) or \
isinstance(pe, _bpimpl('PhysicalEntity'))
return val | 5,288,070 |
def time_function(func: Callable) -> Callable:
"""
Decorator/wrapper function.
Make a function print how long it took to call whenever it is called.
Parameter:
function func: any arbitrary function
Returns:
function timed_func: same function, but now prints its call time... | 5,288,071 |
def paragraphs(text):
"""
Add line breaks to text to implement line breaks
"""
if isinstance(text, SafeData):
return text
text = escape(text)
return mark_safe('<p class="no-margin">{}</p>'.format(text.replace('\n', '</p>\n<p class="no-margin">'))) | 5,288,072 |
def countChrom(ls_chrom):
"""
Counts how often the different chromosomes are present in the list and
returns this as a list.
"""
count = []
for i in LS_CHECK:
count.append(ls_chrom.count(i))
return count | 5,288,073 |
def test_rescale_bounds_incorrect_type(reparam):
"""Assert an error is raised if the rescale_bounds is an invalid type."""
with pytest.raises(TypeError) as excinfo:
RescaleToBounds.__init__(
reparam,
parameters=['x', 'y'],
prior_bounds={'x': [-1, 1], 'y': [0, 1]},
... | 5,288,074 |
def tacacs_auth_lockout(username: str, report_failure: bool = False) -> bool:
"""
Upon a TACACS authentication failure, as seen by Netmiko, update a dict in Redis that holds failures for this user.
And if we've exceeded 10 failures in 10 minutes, lock this user out of the API for 10 minutes
:param usern... | 5,288,075 |
def fold(x: VariableLike,
dim: str,
sizes: Optional[Dict[str, int]] = None,
dims: Optional[Union[List[str], Tuple[str, ...]]] = None,
shape: Optional[Sequence[int]] = None) -> VariableLike:
"""Fold a single dimension of a variable or data array into multiple dims.
:param x: ... | 5,288,076 |
def SaveCoordinate(name,xcenter,ycenter,xdupper,ydupper,xdlower,ydlower):
"""
Save center coordinate, upper contour coordinate, lower contour coordinate
Parameters:
-name: list of name of raw image
-xc: list of x coordinate at center of ROI image
-yc: list of y coordinate at ce... | 5,288,077 |
def _l1m_objective(a,X,*args):
"""
Optimization objective for l1median
"""
return(np.sum(np.apply_along_axis(_euclidnorm,1,_diffmat_objective(a,X)))) | 5,288,078 |
def _new_x_concatenated_sequence(
duration=1.0, concatenation_order=None, pre_post_rotation=False, **kwargs
):
"""
Creates X-Concatenated Dynamic Decoupling Sequence.
Concatenation of base sequence C(\tau/2)XC(\tau/2)X
Parameters
----------
duration : float, optional
defaults to Non... | 5,288,079 |
def addData2matrix(X_train: modALinput, X_new, X_idx, symmetrical) -> modALinput:
"""
Adds the new data to a sparse matrix
Args:
X_train: Training data in sparse format matrix
X_new: Value of new data to be added to training set
X_idx: Set of form (sparse_coordinate, row_idx, col_id... | 5,288,080 |
def load_people(path):
"""Loads a list of people from the path and assigns each default score."""
people = []
with open(path, 'r') as people_file:
for line in people_file.readlines():
people.append(Person(line.strip()))
return people | 5,288,081 |
async def test_set_audio(aresponses: ResponsesMockServer) -> None:
"""Test setting display properties."""
async def response_handler(request: aiohttp.ClientResponse) -> Response:
"""Response handler for this test."""
data = await request.json()
assert data == {
"volume": 99,... | 5,288,082 |
def pathway_genes(pathway: str) -> set:
"""Returns genes for a given pathway in KEGG"""
kgml = _get(pathway, form='kgml').text
# Wrap text in a file handle for KGML parser
f = io.StringIO(kgml)
k = KGML_parser.read(f)
genes = set()
for gene in k.genes:
for x in gene.name.split():
... | 5,288,083 |
def get_availability_domains(identity_client, compartment_id):
"""
Gets the list of AvailabilityDomain for the specified compartment.
:param network_client: OCI VirtualNetworkClient client
:type network_client: oci.core.VirtualNetworkClient
:param compartment_id: The OCID of the compartment to che... | 5,288,084 |
def get_dca_output_file_path(output_dir, msa_file_name, prefix='', postfix=''):
"""Locates the file path to which DCA ouput can be written.
Parameters
-----------
output_dir : str
DCA computation related output directory.
msa_file_name : str
Name of the alignment fil... | 5,288,085 |
def method_authorizations(*scopes: str) -> dict:
"""
Return method security.
Contains only one OAuth2 security.
:param scopes: All scope names that should be available (as string).
"""
return {"security": [{"oauth2": scopes}]} | 5,288,086 |
def glGetProgramiv( baseOperation, program, pname, params=None ):
"""Will automatically allocate params if not provided"""
if params is None:
params = arrays.GLintArray.zeros( (1,))
baseOperation( program, pname, params )
return params[0]
else:
baseOperation( program,pname, p... | 5,288,087 |
def get_aoi_dir(aoi_name):
"""get the result dir associated with the aoi name"""
aoi_dir = result_dir.joinpath(aoi_name)
aoi_dir.mkdir(exist_ok=True)
return aoi_dir | 5,288,088 |
def run_main():
"""
Invokes main() with the contents of sys.argv
This is a separate function so it can be invoked
by a setuptools console_script.
"""
cmd = sys.argv[1] if len(sys.argv) >= 2 else None
opts = [arg_to_option(arg) for arg in sys.argv[2:] if arg.startswith('--')]
try:
... | 5,288,089 |
def np_json_dump(path: str, a: np.ndarray):
"""
Creates a file where json dumps a numpy ndarray then dumps the array using utf-8 encoding
:param path: path to file where numpy array will be dumped
:param a: Numpy Array to json dump
"""
json.dump(a.tolist(), codecs.open(path, 'w', encoding='utf-... | 5,288,090 |
def change_salary(name, new_salary):
"""Change the salary of an employee"""
firstname, lastname = split_name(name)
try:
with Session() as session:
stmt = update(Employee).where(and_(
Employee.firstname == firstname,
Employee.lastname == lastname))
... | 5,288,091 |
def dhcpcap_maker(request):
""" return a function which creates initialized dhcpcap instances. """
def maker():
dhcpcap = DHCPCAP(client_mac="00:01:02:03:04:05", iface='eth0',
xid=900000000)
return dhcpcap
return maker | 5,288,092 |
def validate(config_dir):
"""
Reads config.json in the config_dir and prepopulates with default values.
Ensures that all configured values are of the appropriate types.
Returns (config, message to report if error). Returns None if something
is wrong with the config it read.
"""
config = rea... | 5,288,093 |
def _split(X: TData) -> XData:
"""Split dict into elements."""
Xcon = _make_mask(X["con"], X["con_mask"]) if "con" in X else None
Xcat = _make_mask(X["cat"], X["cat_mask"]) if "cat" in X else None
return XData(Xcon, Xcat, X["indices"], X["coords"]) | 5,288,094 |
def get_address(address):
"""
Request information about a bitcoin address
:param str address: an address hash/id
:return: an instance of Address class
"""
resource = f'address/{address}'
response = util.call_api(resource)
return Address(response) | 5,288,095 |
def loadRectilinearGrid(filename):
"""Load a ``vtkRectilinearGrid`` object from file."""
reader = vtk.vtkRectilinearGridReader()
reader.SetFileName(filename)
reader.Update()
return reader.GetOutput() | 5,288,096 |
def update_rule(request):
"""
Tags: rules
---
Update a rule given its UUID
The expected request body is the same as for the `add_rule` endpoint. The
difference is that none of the parameters are required. Only the specified
parameters will be updated, leaving the rest unchanged.
READ p... | 5,288,097 |
def process_properties(adapter, params):
"""
Process the properties specified in the 'properties' module parameter,
and return a dictionary (update_props) that contains the properties that
can be updated. The input property values are compared with the existing
resource property values and the retur... | 5,288,098 |
def horizontal_dominoes_removed(r, s):
"""
Returns all partitions obtained from a rectangle of width s and height r by removing
horizontal dominoes.
EXAMPLES::
sage: sage.combinat.crystals.kirillov_reshetikhin.horizontal_dominoes_removed(2,2)
[[], [2], [2, 2]]
sage: sage.combin... | 5,288,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.