content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def makedir_exist_ok(dirpath):
"""
Python2 support for os.makedirs(.., exist_ok=True)
"""
try:
os.makedirs(dirpath)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise | 5,320,300 |
def setUpModule():
"""Start server to return test rss data"""
thread = threading.Thread(target=test_server.serve_forever)
thread.daemon = True
thread.start() | 5,320,301 |
def completing(rf, cf=identity):
"""Returns a wrapper around `rf` that calls `cf` when invoked with one argument.
Args:
rf: A :any:`reducing function`.
cf: An optional function that accepts a single argument. Used as the
completion arity for the returned :any:`reducing function`.
... | 5,320,302 |
def build_feet(
filter1, # type: pymunk.ShapeFilter
normal_rect, # type: pygame.Rect
pymunk_objects, # type: List[Any]
body_body, # type: pymunk.Body
seat_body, # type: pymunk.Body
):
# type: (...) -> Tuple[pymunk.Body, pygame.Sprite]
"""
Builds our unicycle cat... | 5,320,303 |
def test_update_experiment_route(initialize_test_db, api_client):
"""Test update experiment records to metadata store"""
response = api_client.put(
"/experiments/EXP:0000002",
json={"id": "EXP:0000002", "name": "Modified Experiment 2"},
)
assert response.status_code == 200
response ... | 5,320,304 |
def zone_distances(zones):
"""
:param zones
GeoDataFrame [*index, zone, geometry]
Must be in a CRS of unit: metre
"""
for ax in zones.crs.axis_info:
assert ax.unit_name == 'metre'
print("Calculating distances between zones...")
distances_meters = pairwise_distances(
list... | 5,320,305 |
def cli():
"""Command line for BDC-Collectors.""" | 5,320,306 |
def _load_attached(builder, detached):
"""
Load config in new session
Parameters
----------
builder: :class:`workspacebuilder.WorkspaceBuilder`
detached : bool
"""
builder.build()
if "TMUX" in os.environ: # tmuxp ran from inside tmux
# unset TMUX, save it, e.g. '/tmp/tmux-... | 5,320,307 |
def compile(r):
""" Turn regular expression into a DFA """
parse(r)
raise NotImplementedError() | 5,320,308 |
def main():
"""
----------
Author: Damon Gwinn (gwinndr)
----------
- Entry point for training a darknet model
----------
"""
args = parse_train_args()
train_imgs = os.path.realpath(args.train_imgs)
train_anns = os.path.realpath(args.train_anns)
val_imgs = os.path.realpath... | 5,320,309 |
def dump(value, file, encoding=None):
"""dump(object,file,encoding=None)
This function dumps a python object as a tnetstring and writes it to
the given file.
"""
file.write(dumps(value, encoding))
file.flush() | 5,320,310 |
def decode_base64(data, altchars=b'+/'):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars,
b'', data.encode())
missing_padding = len(data) % 4
if ... | 5,320,311 |
def _run_after(a, b):
"""Force operation a to run after b. Do not add control dependencies
to ops that already run after. Returns 0 if no dependencies were added,
1 otherwise."""
already_after = (b in a.control_inputs) or (b in [i.op for i in a.inputs])
if already_after:
return 0
ge.reroute.add_contro... | 5,320,312 |
def show_speedup_options_messages(skip_setup):
"""
Skip NIC and spdk setup.
"""
if skip_setup:
log_handler.info('SKIP: Skipping SPDK setup.')
else:
log_handler.info('The SPDK setup steps will be executed.') | 5,320,313 |
def handle_negations(tweet_tokens, lexicon_scores):
"""
Handling of negations occuring in tweets -> shifts meaning of words
-> if a negation was found the polarity of the following words will change
Parameters
----------
tweet_tokens : List
list of tweet tokens that were already prepocessed (... | 5,320,314 |
def build_keras(hyperparams_fn, freeze_batchnorm, inplace_batchnorm_update,
num_predictions_per_location_list, box_predictor_config,
is_training, num_classes, add_background_class=True):
"""Builds a Keras-based box predictor based on the configuration.
Builds Keras-based box pr... | 5,320,315 |
def log_level(non_prod_value: str, prod_value: str) -> str:
"""
Helper function for setting an appropriate log level in prod.
"""
return prod_value | 5,320,316 |
def partitioning_df(stats_df,plus_and_minus,tmp_dir,chunk_size = 1000):
""" the first state for large files is very large. We split the first state in a separate file.
Then all the other states are splitted into several files.
"""
# stats_df.to_csv('stats_df.csv', index=False, header=True, float_form... | 5,320,317 |
def export_results_html(results, output_dir, normalize):
"""
Render HTML files visualising all of the results from the visualiser.
A single HTML file will be generated per result with the filename results_g1_label_g2_label.html.
:param results: results of the visualiser
:type results: list
:par... | 5,320,318 |
def add(x, y):
""" Add two numbers and return their sum"""
return x+y | 5,320,319 |
def _set_annotation_radio_button(idx, params):
"""Set active button."""
radio = params['fig_annotation'].radio
for circle in radio.circles:
circle.set_facecolor('white')
radio.circles[idx].set_facecolor('#cccccc')
_annotation_radio_clicked('', radio, params['ax'].selector) | 5,320,320 |
def create_directory(directory_path: str):
"""
Creates directories using os commands
:param directory_path:
:return:
"""
# adding the directory if it doesn't exist
if not exists(directory_path):
try:
# Create target Directory
mkdir(directory_path)
... | 5,320,321 |
def default_resolve_type_fn(
value: Any,
info: GraphQLResolveInfo,
abstract_type: GraphQLAbstractType
) -> MaybeAwaitable[Optional[Union[GraphQLObjectType, str]]]:
"""Default type resolver function.
If a resolveType function is not given, then a default resolve behavior is
u... | 5,320,322 |
def svn_repos_parse_fns2_invoke_close_node(*args):
"""svn_repos_parse_fns2_invoke_close_node(svn_repos_parse_fns2_t _obj, void * node_baton) -> svn_error_t"""
return _repos.svn_repos_parse_fns2_invoke_close_node(*args) | 5,320,323 |
def psd_5(**kwargs):
"""powerlaw psd, log; no gaps, no alias, noleak, gauss noise
small fq extension; flatter psd
"""
# fqlag parameters #
n = 2**8
dt = 1.0
fql = np.logspace(np.log10(0.8/(dt*n)), np.log10(0.5*dt), 6)
lc, extra = simulate_light_curves(n=n, dt=dt, ns... | 5,320,324 |
def sample_dball(dimension: int, amount: int, radius: float = 1) -> np.ndarray:
"""
**Sample from a d-ball by drop of coordinates.**
Similar to the sphere, values are randomly assigned to each dimension dimension from a certain interval
evenly distributed. Since the radius can be determined... | 5,320,325 |
def distinguishable_paths(path1, path2):
"""
Checks if two model paths are distinguishable in a deterministic way, without looking forward
or backtracking. The arguments are lists containing paths from the base group of the model to
a couple of leaf elements. Returns `True` if there is a deterministic s... | 5,320,326 |
def send_loop(client, q, topic, retry, logger, format_func,
publish_body): # pragma: NO COVER
"""Process loop for indefinitely sending logs to Cloud Pub/Sub.
Args:
client: Pub/Sub client. If it's None, a new client will be created.
q: mp.JoinableQueue instance to get the message from... | 5,320,327 |
def sig_handler(signum, frame):
"""raise exception for SIGTERM
"""
raise SecureUpdateError((1, 'Caught SIGTERM')) | 5,320,328 |
def _correct_rotation(img: np.ndarray) -> np.ndarray:
"""if image is rotated correct for this and return it"""
edges = cv2.Canny(img, 50, 150, apertureSize=3)
lines = cv2.HoughLinesP(
edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10
)
avg_slope = 0
cnt = 0
try:
fo... | 5,320,329 |
def addUser(args):
"""
Inserts user into database with passed CLI arguments
"""
db = _connectDB()
db.execute('INSERT INTO users (name, phone, email) VALUES (?, ?, ?)', (args.name, args.phone, args.email))
db.commit()
db.close()
print "--- User added successfully ---" | 5,320,330 |
def get_xyz_coords(illuminant, observer):
"""Get the XYZ coordinates of the given illuminant and observer [1]_.
Parameters
----------
illuminant : {"A", "D50", "D55", "D65", "D75", "E"}, optional
The name of the illuminant (the function is NOT case sensitive).
observer : {"2", "10"}, optiona... | 5,320,331 |
def test_CWC(A_cwc, b_cwc):
"""
Solve a simple linear program to determine if it is possible to satisfy
A_cwc*[x_task;u_task] <= b_cwc,
and if so how well we can satisfy it.
"""
mp = MathematicalProgram()
xu = mp.NewContinuousVariables(15,1,"xu") # [x_task;u_task]
cost = np.dot(... | 5,320,332 |
def get_progname():
"""Get program name."""
return PurePath(sys.argv[0]).name | 5,320,333 |
async def document_analyze(*, db:AsyncIOMotorClient = Depends(get_database), payload: NoteSchema):
"""[summary]
View inserts item in the document string.
[description]
Endpoint to retrieve an specific item.
"""
analyze = await gensim.result(db, payload)
return fix_item_id(analyze) | 5,320,334 |
def git_aggregate(c):
"""Download odoo & addons git code.
Executes git-aggregator from within the doodba container.
"""
with c.cd(str(PROJECT_ROOT)):
c.run(
"docker-compose --file setup-devel.yaml run --rm odoo", env=UID_ENV,
)
write_code_workspace_file(c)
for git_fo... | 5,320,335 |
def plot_single_correlation(anomlous = False, temporal_resolution = 'monthly', detrend = 'raw', temp_decomp = 'anomalous', imagefolder = 'images/correlations/single/', n = 5, seaice_source = 'nsidc'):
"""Summary
Args:
anomlous (bool, optional): Description
temporal_resolution (str, optional... | 5,320,336 |
def run_gfail(args):
"""Runs ground failure.
Args:
args: dictionary or argument parser Namespace output by bin/gfail
program.
Returns:
list: Names of created files.
"""
# TODO: ADD CONFIG VALIDATION STEP THAT MAKES SURE ALL THE FILES EXIST
filenames = []
# If a... | 5,320,337 |
def create_example_concept_description() -> model.ConceptDescription:
"""
Creates an example :class:`~aas.model.concept.ConceptDescription`
:return: example concept description
"""
concept_description = model.ConceptDescription(
identification=model.Identifier(id_='https://acplt.org/Test_Co... | 5,320,338 |
def plot_histogram_distances():
"""Reads back the sequence of histograms and plots the distance between two consecutive histograms over time"""
list_files = glob.glob(os.path.join(_tmp_path, 'info_*.json'))
list_files.sort()
# the last one contains all the necessary information, -2 is used for tests wh... | 5,320,339 |
def to_int(x):
"""
Try to convert a string to int
:param x: str
:return: int or np.nan
"""
try:
return int(x)
except:
return np.nan | 5,320,340 |
def train_single_batch_agent(agent, train_batch, val_batch, acc_tolerance=1.0, train_loss_tolerance=0.01):
"""
Train untils the accuracy on the specified batch has perfect interpolation in loss and accuracy.
It also prints and tb logs every iteration.
todo - compare with train one batch
:param ac... | 5,320,341 |
def residuals(pars, data):
"""Returns data - model for given values of parameters
Parameters
----------
pars : array-like
[alpha, beta, gamma] parameters.
data : Data object (string)
Data to be compared with model.
"""
alpha, beta, gamma = pars
mod = model(data.x, alp... | 5,320,342 |
def dumpindex(elastic, index, fn):
"""
Helper which dump a whole db and returns in a format handled by bulk api
"""
search = Search(using=elastic, index=index).filter(
"terms", type=["index-pattern", "visualization", "dashboard", "search"]
)
with open(fn, "w+") as fd:
for doc in ... | 5,320,343 |
async def test_delete_setup_messages():
"""Deletes the setup messages."""
cog, _, reaction_for_role_message = init_mocks()
await cog.delete_setup_messages(reaction_for_role_message)
assert tosurnament_mock.SETUP_MESSAGE_MOCK.delete.call_count == 1
assert tosurnament_mock.PREVIEW_MESSAGE_MOCK.delete.... | 5,320,344 |
def update_resource_baseline(resource, date, weeks):
"""calculate all team's resource baseline for the specified date and week period.
if dynamic, always update the baseline,
if fixed, only update if the baseline does not exist
"""
session = requests.session()
for team in Team.objects.all():
... | 5,320,345 |
def write_to_file(filename, path, data, no_new_line=False):
"""Writes str to file"""
logging.info("Writing to %s%s: %s char", path, filename, len(data))
if not os.path.exists(path):
logging.info("Creating %s directory", path)
os.mkdir(path)
with open("%s/%s" % (path, filename), "a", en... | 5,320,346 |
def add_datetime_column(df):
"""Add full datetime column to MCS L2 dataframe.
Using get_time and get_date helpers, combine them into a full datetime
column and add it to the incoming dataframe.
Set index to the new datetime column.
Parameters
----------
df : pd.DataFrame
A MCS data... | 5,320,347 |
def plot_psth_photostim_effect(units, condition_name_kw=['both_alm'], axs=None):
"""
For the specified `units`, plot PSTH comparison between stim vs. no-stim with left/right trial instruction
The stim location (or other appropriate search keywords) can be specified in `condition_name_kw` (default: bilateral... | 5,320,348 |
def load_versions(versions):
"""
parses 'jc221,jc221' etc.
returns the supported versions and orders them
from newest to oldest
"""
props = configparser.ConfigParser()
props.read(LIB_DIR / "sdkversions.properties")
known = list(props["SUPPORTED_VERSIONS"])
filtered = []
for vers... | 5,320,349 |
def market_search_formatter(search_results):
""" Formats the search results into a tabular paginated format
Args:
search_results (list): a list of results in dict format returned from the REST API
Returs:
str: formatted results in tabular format
"""
headers = ["id", "Details", "Cre... | 5,320,350 |
def get_run_dir(run_number: Optional[int] = None) -> Path:
"""
Returns the directory corresponding to a given run number as a Path.
If no run number is provided, return the current run directory.
"""
if run_number is None:
run_number = options.get('current run number')
return runsdir.joi... | 5,320,351 |
def _populate_metadata_graph(graph):
"""Downloads the Project Gutenberg metadata dump and persists it to disk.
"""
graph.open(_METADATA_CACHE, create=True)
with contextlib.closing(graph):
with _download_metadata_archive() as metadata_archive:
for fact in _iter_metadata_triples(metad... | 5,320,352 |
def _delete_test_pod(config_file: str) -> None:
"""
_delete_testrunner_pod deletes the test runner pod
if it already exists.
"""
dev_config = load_config(config_file)
corev1 = client.CoreV1Api()
k8s_conditions.ignore_if_doesnt_exist(
lambda: corev1.delete_namespaced_pod(TEST_POD_NAME... | 5,320,353 |
def test_save_secret():
""" Test that is able to store a secret """
cipher.create_password(store_secret=True)
cipher.save_secret("secret", "hello") | 5,320,354 |
def read_to_ulens_in_intvls(read, intvls):
"""Extract units within `intvls` from `read.units`."""
return [unit.length for unit in read.units
if unit.length in intvls] | 5,320,355 |
def test_processInputs():
"""
Testing processInputs
>>> import warnings
>>> from Products.Five.browser.decode import processInputs
>>> charsets = ['iso-8859-1']
>>> class DummyRequest:
... form = {}
>>> request = DummyRequest()
Strings are converted to unicode::
... | 5,320,356 |
def test_decoding_time():
"""Test TimeDecoding
"""
from sklearn.svm import SVR
if check_version('sklearn', '0.18'):
from sklearn.model_selection import KFold
else:
from sklearn.cross_validation import KFold
epochs = make_epochs()
tg = TimeDecoding()
assert_equal("<TimeDec... | 5,320,357 |
def to_marged_yearly_files(case=1, years=[]):
"""
This method joins all the parameter files and create yearly files
case <int> is a parameter that decieds what files needs to be staged
Case 0 : Binned using Kp and UT, Case 1 : Binned using F10.7 and Kp
"""
params = ["Bx", "By_GSE", "Bz_GSE", "By... | 5,320,358 |
def org_identities_edit(self) -> bool:
"""
### NOT IMPLEMENTED ###
Edit an existing Organizational Identity.
:param self:
:return
501 Server Error: Not Implemented for url: mock://not_implemented_501.local:
"""
url = self._MOCK_501_URL
resp = self._mock_session.get(
url=... | 5,320,359 |
def makePrimes(bits):
"""
Generates the prime numbers p and q.
Param bits: int -- the bit length of each prime
Returns a tuple of prime numbers.
"""
p = None
q = None
for _ in range(500):
p = secrets.randbits(bits)
q = secrets.randbits(bits)
if p != q and p ... | 5,320,360 |
def _in_splice_compatible_env():
"""
Determines if a user is using the Splice Machine managed notebooks or not
:return: Boolean if the user is using the Splice Environment
"""
try:
from beakerx import TableDisplay
import ipywidgets
except ImportError:
return False
re... | 5,320,361 |
def make_split(dataset, holdout_fraction, seed=0, sort=False):
""" Split a Torch TensorDataset into (1-holdout_fraction) / holdout_fraction.
Args:
dataset (TensorDataset): Tensor dataset that has 2 tensors -> data, targets
holdout_fraction (float): Fraction of the dataset that is gonna be in th... | 5,320,362 |
def analyze(df: pd.DataFrame, name: str):
"""
run a full analysis and model comparison given
a DataFrame with multiple results
"""
output_dir = ANALYSES_DIR / name
output_dir.mkdir(parents=True, exist_ok=True)
metrics = df['metric'].unique()
task_tags = df['tag'].unique()
for tag i... | 5,320,363 |
def singleton(instance: str = 'name') -> Callable:
"""
Wrap injector decorator.
:param instance: name of instance to inject
:type instance: str
:return: injector decorator
:rtype: Callable
"""
def save_to_storage(factory_method):
"""
Decorate factory function with depen... | 5,320,364 |
def fillNaToNone(data):
"""Iterates through NA values and changes them to None
Parameters:
dataset (pd.Dataset): Both datasets
Returns:
data (pd.Dataset): Dataset with any NA values in the columns listed changed to None
"""
columns = ["PoolQC", "MiscFeature", "Alley", "Fence", "FireplaceQu... | 5,320,365 |
def presence_handler(cl, prs):
"""
xmpppy presence callback
Args:
cl: the xmpp.Client object
prs: the xmpp.Presence object
"""
source = prs.getFrom().getStripped()
code = prs.getStatusCode()
if code or prs.getType() == "error":
handleChatErrors(source, prs)
handleChatPresences(source, prs) | 5,320,366 |
def test_select_optimal_assignment_mask():
"""Tests the `select_optimal_assignment_mask` function."""
matrix = tf.constant(
[[10.0, 10.0, 0.0], [0.0, 0.0, 15.0], [0.0, 0.0, 0.0]], tf.float32
)
actual_mask = select_optimal_assignment_mask(matrix)
expected_mask_1 = tf.constant(
[[False... | 5,320,367 |
def is_ld_block_defn_line(mdfl):
"""
Parse GFM link definition lines of the form...
[10]: https://www.google.com
[11]: https://www.google.com "Title Info"
[1a]: https://www.google.com "Title Info {}"
[2b]: https://www.google.com "Title Info {biblio info}"
Returns footnot... | 5,320,368 |
def test_check_permissions(mock_list_permissions, mock_dry_permissions):
"""
The view should use the appropriate permissions checks.
"""
view = views.EntryCommentListView()
view.check_permissions(None)
assert mock_dry_permissions.call_count == 1
assert mock_list_permissions.call_count == 1 | 5,320,369 |
def _test_evaluates(lines):
"""
Perform a test case on a given result lines. Compares the result returned
from this library with the results of the original perl script.
Args:
lines: lines of sequence tagging prediction file.
"""
res = report(evaluate(lines))
assert res.strip() == g... | 5,320,370 |
def return_data_frame_deaths_vs_cases(dict_corona_virus: dict, data_frame_countries: pd.DataFrame) -> pd.DataFrame:
"""
This method will return a data_coronavirus frame with the fields we need to create our map with circles:
In this map, the circles will represent the ratio between deaths and number of case... | 5,320,371 |
def vn_islowercase(char):
"""Check is lowercase for a vn character
:param char: a unicode character
:return:
"""
if char in _DIGIT or char in _ADDITIONAL_CHARACTERS:
return True
return char in VN_LOWERCASE | 5,320,372 |
def test_lint():
"""Tests core.lint()"""
passed, notes = core.lint()
assert not passed
assert len(notes) == 5
assert len(notes.commits) == 6
passed, notes = core.lint(range='HEAD..')
assert passed
assert len(notes) == 0
assert len(notes.commits) == 0
passed, notes = core.lint(r... | 5,320,373 |
def validate_snap_configuration(cfg: CharmcraftSnapConfiguration):
"""Validate given snap configuration.
:raises ValueError: on error.
"""
if cfg.provider is not None and cfg.provider not in ["lxd", "multipass"]:
raise ValueError(f"provider {cfg.provider!r} is not supported") | 5,320,374 |
def shared_template(testconfig):
"""Shared template for hyperfoil test"""
shared_template = testconfig.get('hyperfoil', {}).get('shared_template', {})
return shared_template.to_dict() | 5,320,375 |
def doubleSlit_interaction(psi, j0, j1, i0, i1, i2, i3):
"""
Function responsible of the interaction of the psi wave function with the
double slit in the case of rigid walls.
The indices j0, j1, i0, i1, i2, i3 define the extent of the double slit.
slit.
Input parameters:
... | 5,320,376 |
def gnp_from_data(sizes, densities, directed = True):#, p_disconnect_node = None):
"""
Given a set of graph sizes (number of nodes) and densities, generate a new gnp (Bernoulli/Erdos-Renyi) random graph with size selected from the given graph sizes. Density is estimated based on a linear model of the observed s... | 5,320,377 |
def greedy_tsp(G, weight="weight", source=None):
"""Return a low cost cycle starting at `source` and its cost.
This approximates a solution to the traveling salesman problem.
It finds a cycle of all the nodes that a salesman can visit in order
to visit many nodes while minimizing total distance.
It... | 5,320,378 |
def get_sector(sector_id):
"""
GET: Gets all Entities on the required sector.
https://meinformoapi.herokuapp.com/entities/sectors/Ejecutivo
"""
sector_id = str(sector_id)
output = tools.filter_dict(current_entities,"sector", [sector_id])
return Response(dumps(output), mimetype='application/j... | 5,320,379 |
def set_env_variable(env: str, value: str):
"""Sets a new value for an environmental variable
:param env: Environmental variable to be set
:type env: str
:param value: Value to be set
:type value: str
"""
os.environ[env] = value
imp.reload(SwissKnife.info) | 5,320,380 |
def map_get_by_key_range(bin_name, key_range_start,
key_range_end, return_type, inverted=False):
"""Creates a map_get_by_key_range operation to be used with operate or operate_ordered
The operation returns items with keys between key_range_start(inclusive) and
key_range_end(exclusi... | 5,320,381 |
def output(input_text : str = ""):
"""
It will take input as a string and return the output of the given input mathematics problem
"""
cal_object = Calculator(input_text)
return cal_object.result | 5,320,382 |
def to_tensor(X, use_cuda):
"""Turn to torch Variable.
Handles the cases:
* Variable
* PackedSequence
* numpy array
* torch Tensor
* list or tuple of one of the former
* dict of one of the former
"""
to_tensor_ = partial(to_tensor, use_cuda=use_cuda)
if isinsta... | 5,320,383 |
def get_regularization_losses(scope=None):
"""Gets the list of regularization losses.
Args:
scope: An optional scope name for filtering the losses to return.
Returns:
A list of regularization losses as Tensors.
"""
return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope) | 5,320,384 |
def get_output_tracking_error_message(ulog: ULog) -> str:
"""
return the name of the message containing the output_tracking_error
:param ulog:
:return: str
"""
for elem in ulog.data_list:
if elem.name == "ekf2_innovations":
return "ekf2_innovations"
if elem.name == "e... | 5,320,385 |
def getBpms():
"""
return a list of bpms object.
this calls :func:`~aphla.lattice.Lattice.getGroupMembers` of current
lattice and take a "union".
"""
return machine._lat.getGroupMembers('BPM', op='union') | 5,320,386 |
def get_test_disk(node=1):
"""获取可测试使用的磁盘
Args:
node (int, optional): 节点号. Defaults to 1.
Returns:
[str]: 磁盘名称
"""
if os.environ.get("NODE" + str(node) + "LOCALTION") == "local":
used_disk = subprocess.getoutput(
"lsblk -l | grep -e '/.*\|\[.*\]' | awk '{print $1... | 5,320,387 |
def get_single_label(label_id):
"""Get an ID as a single element.
Args:
label_id: Single ID or sequence of IDs.
Returns:
The first elements if ``label_id`` is a sequence, or the
``label_id`` itself if not.
"""
if libmag.is_seq(label_id) and len(label_id) > 0:
... | 5,320,388 |
def search_sentinels(platform_name, df, aoi, dt=2, user=None, pwd=None,
proj_string='+init=EPSG:3995', product_type=None,
min_cloud_cover=0, max_cloud_cover=100,
swath_type=None, f_out=None):
"""
Search Sentinel-1/2 images overlapping ICESat-2 data ... | 5,320,389 |
def not_implemented(cls):
"""Decorator for TestCase classes to indicate that the tests have not been written (yet)."""
msg = "%s: tests have not been implemented" % cls.__name__
_NOT_IMPLEMENTED.append(msg)
return unittest.skip(msg)(cls) | 5,320,390 |
def add_roles(uid, *args): # TODO(e-carlin): roles arg
"""Assign roles to a user
Args:
uid (str): Uid of the user
*args: The roles to assign to the user
"""
_check_uid_and_roles(uid, args)
sirepo.auth_db.UserRole.add_roles(uid, args)
admin.audit_proprietary_lib_files(uid) | 5,320,391 |
def drop_with_revoked_privilege(self, grant_target_name, user_name, node=None):
"""Revoke DROP VIEW privilege and check the user is unable to DROP a view.
"""
view_name = f"view_{getuid()}"
exitcode, message = errors.not_enough_privileges(name=f"{user_name}")
if node is None:
node = self.co... | 5,320,392 |
def get_default_container_image_for_current_sdk(job_type):
"""For internal use only; no backwards-compatibility guarantees.
Args:
job_type (str): BEAM job type.
Returns:
str: Google Cloud Dataflow container image for remote execution.
"""
# TODO(tvalentyn): Use enumerated type instead of strings for... | 5,320,393 |
def get_structure_tuple(fileobject, fileformat, extra_data=None):
"""
Given a file-like object (using StringIO or open()), and a string
identifying the file format, return a structure tuple as accepted
by seekpath.
:param fileobject: a file-like object containing the file content
:param filefor... | 5,320,394 |
def test_capacity_class(capacity):
"""
Test least cost xmission and compare with baseline data
"""
truth = os.path.join(TESTDATADIR, 'xmission',
f'least_cost_{capacity}MW.csv')
sc_point_gids = None
if os.path.exists(truth):
truth = pd.read_csv(truth)
sc_p... | 5,320,395 |
def find_merge_commit_in_prs(needle, prs):
"""Find the merge commit `needle` in the list of `prs`
If found, returns the pr the merge commit comes from. If not found, return
None
"""
for pr in prs[::-1]:
if pr['merge_commit'] is not None:
if pr['merge_commit']['hash'] == needle[1... | 5,320,396 |
def date_breaks(width):
"""
Regularly spaced dates
Parameters
----------
width:
an interval specification. must be one of [minute, hour, day, week, month, year]
Examples
--------
>>> date_breaks(width = '1 year')
>>> date_breaks(width = '6 weeks')
>>> date_breaks('month... | 5,320,397 |
def create_valid_url(url: str) -> str:
"""
Generate a video direct play url.
"""
return url | 5,320,398 |
def circular_weight(angle):
"""This function utilizes the precomputed circular bezier function
with a fit to a 10th order curve created by the following code block:
.. code-block:: python
x = numpy.arange(.5, 180, 0.5)
y = []
for i in x:
y.append(bezier.find_circular_we... | 5,320,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.