content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def equal_angle_stereographic_projection_conv_YZ_plane(x,y,z):
"""Function to take 3D grid coords for a cartesian coord system and convert to 2D equal area projection."""
Y = y/(1+x)
Z = z/(1+x)
return Y,Z | 50,400 |
def download_past_trees(test: bool, number: int):
"""
Download a number of past trees
:param number: number of trees to download from the latest
"""
trees = []
key = "badger-tree.json"
bucket = env_config.bucket
response = s3.list_object_versions(Prefix=key, Bucket=bucket)
versions =... | 50,401 |
def read_init_values(srclines, init_names=None):
""" srclines - an ODE-file content in the list of strings,
if init_names is None all parameters will be read
init_names - the list of parameters names
return:
the dict of parameters, where keys=pars_names, values are parsed from srclines
"""
... | 50,402 |
def getCategorySentiments(termSentiData,trainLexicon,finalDF):
"""
Module to extract category-wise sentiment scores and
generate final dataframe with predicted and true sentiment
Args:
termSentiData: dictionary of aspect terms and its sentiment
trainLexicon: Lexicon of defining ter... | 50,403 |
def get_test_pipeline():
"""Return an arbitrary pipeline definition."""
return {
'sg1': [
'step1',
'step2',
{'step3key1': 'values3k1', 'step3key2': 'values3k2'},
'step4'
],
'sg2': False,
'sg3': 77,
'sg4': None
} | 50,404 |
def networking_action():
"""Commands related to networking-actions""" | 50,405 |
def get_package_type(name):
"""
Returns the package type. Available package types are defined in PackageType.
Only ASR9K supports Service Packs concept
Example: asr9k-px-4.3.2.sp-1.0.0 or asr9k-px-4.3.2.k9-sp-1.0.0
"""
if name.find(SMU_INDICATOR) != -1:
return PackageType.SMU
... | 50,406 |
def _delayedinterrupt():
"""Block signal interrupt while doing something critical
This makes sure that the code block wrapped by this context manager won't
be interrupted.
For Windows developers: It appears not possible to guard time.sleep()
from CTRL_C_EVENT, so please don't use time.sleep() to t... | 50,407 |
def merge(df1, df2, on=None, how="left"):
"""
DESCRIPTION
-----------
Merge two pandas dataframes on a common field name or specified fields in
each frame.
PARAMETERS
----------
df1 : pd.DataFrame
A pandas dataframe instance
df2 : pd.DataFrame
A pandas dataframe ins... | 50,408 |
def resident_required(a_view):
"""居住者権限を持つユーザのみ実行を許可する
居住者権限を持つユーザとは 1 つ以上の community.Unit と関連づけられたユーザ.
不許可なら 403 Forbidden を返す.
Args:
a_view (func): ビュー関数
"""
def _wrapped_view(request, *args, **kwargs):
if request.user.unit_set.count():
return a_view(request, *args, **kwargs)
else:
return HttpRes... | 50,409 |
def get_movie(id):
"""
Given a movie ID, return a movie with that ID, with the comments for that
movie embedded in the movie document. The comments are joined from the
comments collection using expressive $lookup.
"""
try:
"""
Ticket: Get Comments
Please implement a $lo... | 50,410 |
def _stdout_logging(level):
"""Setup logging to stdout and return logger's `info` method.
"""
formatter = logging.Formatter(
'%(levelname)s %(asctime)s %(module)s %(funcName)s(): %(message)s',
'%Y-%m-%d %H:%M:%S')
stdout = logging.StreamHandler()
stdout.setLevel(level)
stdout.set... | 50,411 |
def standardize_phone(raw: str) -> str:
"""Make sure it's 10 digits, remove everything else
>>> standardize_phone("(555) 555-1212")
'5555551212'
"""
raw = [x for x in raw if x.isnumeric()]
raw = "".join(raw)
if len(raw) != 10:
raw = None
return raw | 50,412 |
async def find(req):
"""
Get a list of all existing group documents.
"""
cursor = req.app["db"].groups.find()
return json_response([virtool.utils.base_processor(d) async for d in cursor]) | 50,413 |
def _sub_seg(out_dir, pic_path, stack_model, clip):
"""线程任务"""
global fail, success, skip, count, total, predictRet
info = "starting process : %s" % pic_path
logger.info(info)
img_dirs = os.path.join(out_dir, pic_path.split("\\")[-1])
if os.path.isfile(api.getName(img_dirs, "_new")):
ski... | 50,414 |
def word_guessed():
"""
Returns True if the player has successfully guessed the word,
and False otherwise.
"""
global secret_word
global letters_guessed
####### YOUR CODE HERE ###### | 50,415 |
def _load_path(config_file: Path, reload: bool):
"""Load (or reload) the file/directory in the memory
>>> import tempfile; tmp_file = tempfile.mktemp()
>>> with open(tmp_file, "w") as out:
... out.write('{"answer": 42}')
14
>>> get(tmp_file)["answer"]
42
>>> with open(tmp_file, "w")... | 50,416 |
def test_empty():
"""
PageViewBase validate required attributes
"""
with pytest.raises(ViewImproperlyConfigured):
PageViewBase() | 50,417 |
def template_readable_response(responses: Union[dict, List[dict], str]) -> Union[str, List[Dict[str, Any]]]:
"""
Creates a readable response for responses that have fields in the form of:
{
'defaultValue': null,
'editable': true,
'key': 'sr_type',
'keyCapt... | 50,418 |
def rehtml(content):
"""
does unicode bullshit
:param content:
:return:
"""
doc = UnicodeDammit(content, is_html=True)
parser = ht.HTMLParser(encoding=doc.original_encoding)
root = ht.fromstring(content, parser=parser)
return root | 50,419 |
def center_film(structure):
"""
Centers a film at z=0
Args:
structure: AiiDA structure
returns: AiiDA structure
"""
if structure.pbc != (True, True, False):
raise TypeError('Only film structures having surface normal to z are supported')
sorted_struc = sort_atoms_z_value(... | 50,420 |
def start_gpu_process(process_id,
gpu_id,
designs,
domain='ant',
data_folder="data/",
max_episode_steps=1000,
n_envs=4,
total_timesteps=1000000):
"""Train many po... | 50,421 |
def get_stop_response():
""" end the session, user wants to quit the game """
speech_output = STOP_MESSAGE
return response(speech_response(speech_output, True)) | 50,422 |
def test_zeros_like(func_interface):
"""Tests for numpoly.zeros_like."""
poly = numpoly.polynomial([1, X, 2])
assert_equal(func_interface.zeros_like(poly), [0, 0, 0])
assert_equal(numpoly.zeros_like([1, X, 2]), [0, 0, 0])
poly = numpoly.polynomial([1., X, 2])
assert_equal(func_interface.zeros_li... | 50,423 |
def __extract_clusters_from_html(html):
"""Parse the clusters of a balancer manager page.
:param html: The raw HTML of the balancer manager page.
:returns: a list of clusters.
"""
clusters = []
for section in re.findall('(<h3>.+?)<hr />', html.replace('\n', '')):
cluster = _parse_cluste... | 50,424 |
def _value_to_int(value: Union[int, str]) -> int:
"""String value to int."""
try:
return int(value)
except ValueError as error:
raise Exception("The value is not integer") | 50,425 |
def clean() -> None: # pragma: no cover
"""Remove outputs in jupyter notebooks (before committing to git)."""
for (folder, _, files) in os.walk(
kineticstoolkit.config.root_folder + '/doc'):
if '/_build' in folder or '/.ipynb_checkpoints' in folder:
for file in files:
... | 50,426 |
def era5_temp_anomalies(obs_directory, save_directory, start_range='1999-01-01', end_range='2019-12-31',
save=False, author=None):
"""
Create ERA5 temperature hindcast anomalies.
Args:
obs_directory (str): Directory where files are located.
save_directory (str): ... | 50,427 |
def is_supported(browser):
"""
指定したブラウザがサポート対象かチェック
Attributes:
browser (str): チェック対象ブラウザ
Returns:
bool: ブラウザのサポート有無
"""
return browser in _browser_modules | 50,428 |
def pie_marker(
ratios: Sequence[float],
res: int = 50,
direction: str = "+",
start: float = 0.0,
) -> Tuple[list, list]:
"""
Create each slice of pie as a separate marker.
Parameters:
ratios(list): List of ratios that add up to 1.
res: Number of ... | 50,429 |
def indref_dust_wolff_2009(wav):
"""
This function returns the index of refraction for dust.
The data used are nominally taken from Wolff (2009), which extends from 236 nm to 98.5423 micron. There are only 5 points in our wavelength region of interest.
For the moment, we use the compendium provided by the Ames GC... | 50,430 |
def copy_rules(ctx, institution, requirement_id):
"""
copy_rules : COPY_RULES expression SEMICOLON?;
The expression is a requirement_id enclosed in parentheses (RA######).
"""
if DEBUG:
print(f'*** copy_rules({class_name(ctx)}, {institution}, {requirement_id})',
file=sys.stderr... | 50,431 |
def select_columns(
df: pd.DataFrame,
*args,
invert: bool = False,
) -> pd.DataFrame:
"""
Method-chainable selection of columns.
Not applicable to MultiIndex columns.
It accepts a string, shell-like glob strings `(*string*)`,
regex, slice, array-like object, or a list of the previous o... | 50,432 |
def compute_distance(location_1, location_2):
"""
Euclidean distance between 3D points.
Parameters
----------
location_1 : carla.Location
Start point of the measurement.
location_2 : carla.Location
End point of the measurement.
"""
x = location_2.x - location_1.x
y ... | 50,433 |
def ewma_2d(x, halflife):
"""
Exponentially Weighted Moving Average,
optimised for 2D data sets.
"""
assert x.ndim == 2
assert np.isfinite(halflife) and halflife > 0
decay_coefficient = np.exp(np.log(0.5) / halflife)
out = np.empty_like(x, dtype=np.float64)
for i in range(out.shape... | 50,434 |
def DT2str(dt):
"""
convert a datetime to a string in the GNOME format.
"""
dt_string = "%3i, %3i, %5i, %3i, %3i"%(dt.day, dt.month, dt.year, dt.hour, dt.minute)
return dt_string | 50,435 |
def fetch_mobilisation():
"""Fetch mobilisation submissions."""
formid = getattr(settings, "MOBILISATION_FORM_ID", None)
if formid:
data_ids = get_missing_ids(formid, Mobilisation)
for data_id in data_ids:
data = fetch_form_data(formid, dataid=data_id)
if data:
... | 50,436 |
def get_active_lines(lines, comment_char="#"):
"""
Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List o... | 50,437 |
def is_shutout(goalie_dict, goalies_in_game):
"""
Checks whether current goalie game can be considered a shutout.
"""
# only goalies that played and didn't concede any goals can have a shutout
if (goalie_dict['games_played'] and not goalie_dict['goals_against']):
# if more than two goalies (... | 50,438 |
def phase_segmentation(image, threshold, area_bounds=[0.5, 6.0],
ip_dist=0.160):
"""
Segement a phase image and return the mask.
Parameters
----------
image : 2d-array
The phase image to be segmented. This image will be converted to a
float type.
threshold... | 50,439 |
def _fix_other_columns(df):
"""
Fills all other columns using reasonably similar rows.
"""
cols_to_fill1 = [
"season",
"workingday",
"weathersit",
"temp",
"atemp",
"hum",
"windspeed",
"cnt",
]
dhour = datetime.timedelta(hours=1)
... | 50,440 |
def storage_get_all_by_project(context, project_id, marker, limit, sort_key,
sort_dir):
"""Get all storages belonging to a project."""
return IMPL.storage_get_all_by_project(context, project_id, marker, limit,
sort_key, sort_dir) | 50,441 |
def evaluate_parentheses(token):
"""
Evaluates parentheses.
Parameters
----------
token : ``Token``
Returns
-------
new_token : ``Token``
The final evaluated token.
"""
new_token = evaluate_tokens(token.sub_tokens)
new_token.start = token.start
new_token... | 50,442 |
def export_dataset(df):
"""Exports data as 'ahs.csv' to data folder"""
print("Exporting data as 'ahs.csv' to data folder")
df.to_csv('data/ahs.csv', index=False)
print('Done!') | 50,443 |
def test_get_legacy_lb_empty(mocker):
"""
Test lb.legacy.list task without service returned by API
"""
mocker.patch(
'ovh_api_tasks.api_wrappers.ip.get_ip_lb_services', return_value=[])
lb_legacy_tasks.get_legacy_lb(MockContext())
output = sys.stdout.getvalue()
assert re.search(
... | 50,444 |
def test_cli_works_from_random_directory_with_c_flag_great_expectations_directory(
monkeypatch, empty_data_context, tmp_path_factory
):
"""We don't care about the NOUN here just combinations of the config flag"""
context = empty_data_context
runner = CliRunner(mix_stderr=True)
temp_dir = tmp_path_fa... | 50,445 |
def test_export_jpeg_ext_edited_movie():
"""test --jpeg-ext doesn't change extension on edited movie (issue #366)"""
import glob
import os
import os.path
from osxphotos.cli import export
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not-context-manager
with runner.isolat... | 50,446 |
def typprice(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of typical price for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): T... | 50,447 |
def evaluate_grants(path_to_gt_json, path_to_test_json):
"""
This function measures the micro recall of the grantIDs identified by a system.
Input:
- gt_json: Path to ground truth .json file
- test_json: Path to user submitted .json file
Output:
- Float value of micro recall ... | 50,448 |
def main(name=None, grade=None):
"""Produce a school report either by selecting randomly from
preset lists or by accepting a name and a numeric grade. The
name will be passed through directly; the grade will result
in one of a set of appropriate pieces of text.
The parameters can be passed on the c... | 50,449 |
def read_puzzle(board, input_puzzle):
"""
Reads unsolved puzzle
If the string given is a filename with .txt of .sud suffix, the puzzle
is read from the file, otherwise a string containing the puzzle is considered
Expected format:
1 line, row-wise saved values where unknown cells are marked with
... | 50,450 |
def dataclass_from_dict(klass, d):
"""
Converts a dictionary based on a dataclass, into an instance of that dataclass.
Recursively goes through lists, optionals, and dictionaries.
"""
if is_type_SpecificOptional(klass):
# Type is optional, data is either None, or Any
if not d:
... | 50,451 |
def depolarization_factor(wl):
"""Bucholtz 95 Table 1
Depolarization factor as fct of wavelength in nm"""
rho = np.array([[0.200, 4.545],
[0.205, 4.384],
[0.210, 4.221],
[0.215, 4.113],
[0.220, 4.004],
... | 50,452 |
def draw_line (surface, color, a, b, width=1):
"""draw_line (...) -> Rect
Draws a line on a surface.
The 'color' argument needs to match the pygame color style. 'a' and
'b' are sequences of the x- and y-coordinate on the surface and
'width' denotes the width of the line in pixels. The return valu... | 50,453 |
def validate_args(config, args):
"""Make sure all required database args are provided"""
required_db_args = [
"postgres_name", "postgres_db",
"postgres_user", "postgres_password",
"postgres_port",
"postgres_data_dir",
]
if "database" in config._sections:
for var i... | 50,454 |
def rows2csv(rows):
"""http://stackoverflow.com/a/9157370"""
import io
import csv
if sys.version_info[0] <= 2:
#python2 version of csv doesn't support unicode input
#so use BytesIO instead
#https://stackoverflow.com/a/13120279
#TODO: does StringIO.StringIO work?
o... | 50,455 |
def judge_all_tests(judge: LocalJudge, verbose_level, score_dict, total_score):
"""Judge all tests for given program.
If `--input` is set, there is only one input in this judgement.
"""
judge.build()
report = Report(
report_verbose=verbose_level, score_dict=score_dict, total_score=total_s... | 50,456 |
def test_delGlobal():
"""Del a global binding from a function."""
flakes('''
a = 1
def f():
global a
del a
a
''') | 50,457 |
def generate_per_sample_fastq_command(forward_seqs, reverse_seqs, barcode_fps,
mapping_file, output_dir, params_str):
"""Generates the per-sample FASTQ split_libraries_fastq.py command
Parameters
----------
forward_seqs : list of str
The list of forward seq... | 50,458 |
def test_interpolate_pose() -> None:
"""Interpolate poses between the time interval [0,1].
Note: visualization may be turned on to understand the setup. See figure here:
https://user-images.githubusercontent.com/16724970/155865211-cee5f72c-a886-4d47-bc75-65feb3b41fe6.png
Two coordinate frames @t0 ... | 50,459 |
def renderInlineStyle(d):
"""If d is a dict of styles, return a proper style string """
if isinstance(d, (str, int, float)):
result = str(d)
else:
style=[]
for k,v in d.items():
style.append("{}:{};".format(k, v))
separator = ' '
result = separator.join(st... | 50,460 |
def selftest(silent: bool=False) -> bool:
"""Run a simple self-test of DHParser.
"""
if not silent:
print("DHParser selftest...")
print("\nSTAGE I: Trying to compile EBNF-Grammar:\n")
builtin_ebnf_parser = get_ebnf_grammar()
docstring = str(builtin_ebnf_parser.__doc__) # type: str
... | 50,461 |
def bounding_box(grid, cell_kji0, points_root = None, cache_cp_array = False):
"""Returns the xyz box which envelopes the specified cell, as a numpy array of shape (2, 3)."""
result = np.zeros((2, 3))
cp = grid.corner_points(cell_kji0, points_root = points_root, cache_cp_array = cache_cp_array)
result[... | 50,462 |
def sample_pauli_base(rho, pauli_term, epsilon, base_shots=5000, debug=False,
disp=True):
"""
Sample using the inverse transform sampling technique
:param rho: density matrix of state.
:param pauli_term: operator to measure.
:param epsilon: absolute precision. The standard er... | 50,463 |
def print_message(msg: str, height: int):
"""
Prints msg in a zig-zag horizontal pattern across the screen, with the specified height.
:param msg: the message to use to populate the array
:param height: the height of the array
"""
array = form_array(msg, height)
rows = [''.join(row) for row ... | 50,464 |
def exit_json(_, **kwargs):
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs) | 50,465 |
def test_dup_args_in_call(x):
"""The naive gradient update rule fails when a function's arguments
contain the same variable more than once."""
return x * x | 50,466 |
def debug_data(seq_source_ids, seq_ref_ids, seq_source_len, seq_ref_len, id_to_vocab):
"""Debug dataset batch samples to ensure they take on intended avlues"""
logging.info("==============================================================")
logging.info("SOURCE!")
#logging.info(seq_source_ids)
for sou... | 50,467 |
def _predict_while_waiting_for_first_monitoring_job_to_complete(predictor, monitor):
"""Waits for the schedule to have an execution in a terminal status.
Args:
monitor (sagemaker.model_monitor.ModelMonitor): The monitor to watch.
"""
for _ in retries(
max_retry_count=200,
excep... | 50,468 |
def snake_to_camel_case(snake_text):
"""
Converts snake case text into camel case
test_path --> testPath
:param snake_text:str
:return: str
"""
components = snake_text.split('_')
# We capitalize the first letter of each component except the first one with
# the 'title' method and j... | 50,469 |
def setup_zones():
"""Setup availability zones."""
setup_esx_zone() | 50,470 |
def compute_accuracy(dist, labels, threshold):
"""
Compute the average accuracy over the given set of images.
dist: computed distance between pair of images.
labels: true class labels
threshold: decision threshold.
"""
trueclass = np.sum(np.logical_and((dist <= threshold)... | 50,471 |
def add_athena_proc_number(cmd):
"""
Add the ATHENA_PROC_NUMBER and ATHENA_CORE_NUMBER to the payload command if necessary.
:param cmd: payload execution command (string).
:return: updated payload execution command (string).
"""
# get the values if they exist
try:
value1 = int(os.e... | 50,472 |
def _maybe(repo_rule, name, **kwargs):
"""Executes the given repository rule if it hasn't been executed already.
Args:
repo_rule: The repository rule to be executed (e.g., `http_archive`.)
name: The name of the repository to be defined by the rule.
**kwargs: Additional arguments passed direct... | 50,473 |
def http_take_solver():
"""Return the string of answer"""
request_data = request.get_json()
answers = ai.take_solver(request_data)
return jsonify({"answers": answers}) | 50,474 |
def import_gwhod(path=gs_path):
"""
Procedure to read in data from the George Washington University Human Origins Database
:param path:
:return:
"""
data_file = open(path, 'U')
lines = data_file.readlines()
data_file.close()
for line in lines[410:]: # skip header
data = line... | 50,475 |
def from_search(search_string):
"""This prints the result from a shodan search with a given string"""
# Developer Shodan API key
shodan_key_string = open(config_params.SHODAN_KEY_FILE).readline().rstrip('\n')
# Connecting to the SHODAN DB
shodan_api = shodan.Shodan(shodan_key_string)
try:
... | 50,476 |
def create_organization(
*, db_session: Session = Depends(get_db), organization_in: OrganizationCreate
):
"""
Create a new organization.
"""
organization = get_by_name(db_session=db_session, name=organization_in.name)
if organization:
raise HTTPException(
status_code=400, det... | 50,477 |
def check_all(logic_forms: list, checks=None, verbose=False) -> list:
""" Do all Logic Form Graph checking.
Parameter:
logic forms (list): logical forms
verbose (bool): enable printing details
Returns:
lf_graphs (list): dicts of id (int) and a graph (LogicalFormGraph)
"""
lf_graphs = ... | 50,478 |
def remove_noise(line,minsize=8):
"""Remove small pixels from an image."""
if minsize==0: return line
bin = (line>0.5*amax(line))
labels,n = morph.label(bin)
sums = measurements.sum(bin,labels,range(n+1))
sums = sums[labels]
good = minimum(bin,1-(sums>0)*(sums<minsize))
return good | 50,479 |
def get_wide_dword(*args):
"""
get_wide_dword(ea) -> uint64
Get two wide words (4 'bytes') of the program at 'ea'. Some processors
may access more than 8bit quantity at an address. These processors
have 32-bit byte organization from the IDA's point of view. This
function takes into account order of bytes ... | 50,480 |
def corrupt(x, mask=None):
"""Take an input tensor and add uniform masking.
Parameters
----------
x : Tensor/Placeholder
Input to corrupt.
mask: none
Returns
-------
x_corrupted : Tensor
50 pct of values corrupted.
"""
import copy
cor = copy.deepcopy(x)
i... | 50,481 |
def _set_fixed(o, d):
"""
Set if variable is fixed, used for read fixed attribute callback.
Args:
o: object whose attribute is to be set
d: attribute value
Returns:
None
"""
if d:
o.fix()
else:
o.unfix() | 50,482 |
def test_track_module_with_limited_submodules():
"""Test that the submodules arg can be passed through"""
sample_lib_mapping = import_tracker.track_module(
"sample_lib",
recursive=True,
submodules=["sample_lib.submod1"],
)
assert sample_lib_mapping == {
"sample_lib": sort... | 50,483 |
def bvi(model, guide, claims, learning_rate=1e-5, num_samples=1):
"""perform blackbox mean field variational inference on simpleLCA.
This methods take a simpleLCA model as input and perform blackbox variational
inference, and returns a list of posterior distributions of hidden truth and source
reliabil... | 50,484 |
def load_metadata(bucket: str, prefix: str) -> dict[str, dict]:
"""
Get general export metadata file and table status metadatas. The
former contains column names / types as well as a string containig
schema and table name.
Export metadata contains info about the overall RDS snapshot export. For
... | 50,485 |
def get_dbtbl(options: list):
"""Handles dbtbl (available lobby table) calls."""
main.terminate_incorrect_lobbies()
order = None
resort = None
for option in options:
option = option.strip("'")
if option.startswith("order="):
order = option[6:]
elif option.startswi... | 50,486 |
def semiperfect() -> Iterable[int]:
"""Semiperfect numbers."""
for n in count(start=1):
if is_semiperfect(n):
yield n | 50,487 |
def compare_parsed_text(seq_list, auto_stripped_text):
"""
This is a stupid workaround to the fact that bs4 parsers generally suck.
Tries to measure whether parsing was "successful" by looking at the
automatically scraped text of the policy to the text we parse here.
Note: can't match/replace entir... | 50,488 |
def repmi(instr, marker, value, lenout=None):
"""
Replace a marker with an integer.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmi_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type marker: str
:param value: Replacement value.... | 50,489 |
def _get_parameter_state(sender_owner, sender_type, param_name, component):
"""Return ParameterState for named parameter of a Mechanism requested by owner
"""
# Validate that component is a Mechanism or Projection
if not isinstance(component, (Mechanism, Projection)):
raise ParameterStateError(... | 50,490 |
def start_volume( mdserver_name ):
"""
Start up an existing metadata server for a volume. Return 1 on success.
"""
global conf
ctl_root = VOLUME_CTL_ROOT( conf, {'NAME': mdserver_name} )
config_file = VOLUME_CONF_PATH( ctl_root )
md_logfile = LOGFILE_PATH( ctl_root )
md_pidfile = PIDFIL... | 50,491 |
def test_group_management_operation_drop(group):
"""Test the build_query method for a DROP operation."""
op = GroupManagementOperation(
operation=Operation.DROP,
subject=group,
privilege=None,
)
result = op.build_query()
expected = "DROP GROUP a_user_group_1;"
assert re... | 50,492 |
def _pycall_path_dest_only(
x1: int, y1: int, x2: int, y2: int, handle: Any
) -> float:
"""A TDL function which samples the dest coordinate only."""
return ffi.from_handle(handle)(x2, y2) | 50,493 |
def calculate_leap_seconds(year, month, day):
"""
get the leap seconds for the given year to convert GPS time to UTC time
.. note:: GPS time started in 1980
.. note:: GPS time is leap seconds ahead of UTC time, therefore you
should subtract leap seconds from GPS time to get UTC time.
... | 50,494 |
def convert_vpc_name_to_vpc(possible_vpc_id, error_on_exit=True):
""" Convert a given VPC name into the VPC ID.
If the input VPC name looks like an existing VPC ID, then return the VPC immediately.
If the VPC with the given VPC name exists, then return the VPC.
If there is no such VPC, it pr... | 50,495 |
def preprocess_person(hh_dat, person_dat):
"""
This function preprocesses person-level features and merge with household data.
Nominal categorical variables, such as years of age are
transformed into continuous values.
Input:
Preprocessed household-level data
Original perosn-le... | 50,496 |
def from_file(archive: PathOrTarFile) -> Optional[Dict]:
"""Load and parse CRAN package archive
Args:
archive (PathOrTarFile): path to archive or `tarfile.TarFile` instance
Returns:
(dict): Dictionary of R package metadata
"""
return decode(read_description(archive)) | 50,497 |
def save_mesh_file(mesh, fptr):
"""
SAVE-MESH-FILE: save a JIGSAW mesh object to *.OFF file.
"""
nnum = {
"PT": 0, "E2": 0, "T3": 0,
"Q4": 0, "T4": 0, "H8": 0,
"W6": 0, "P5": 0}
if (mesh.vert2 is not None):
nnum["PT"] += mesh.vert2.size
if (mesh.vert3 is not Non... | 50,498 |
def to_google_cloud_bigquery(pandas_gbq_schema):
"""Given a schema in pandas-gbq API format,
return a sequence of :class:`google.cloud.bigquery.schema.SchemaField`.
"""
from google.cloud import bigquery
# Need to convert from JSON representation to format used by client library.
schema = add_de... | 50,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.