content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_remote_filesystem_and_path(
protocol: str, uri: str, path: str, **storage_options: Dict[str, Any]
) -> Tuple[AbstractFileSystem, str]:
"""
For a given protocol, root uri, path and kwargs returns the appropriate FileSystem representation and the
representation of path on this FileSystem required ... | 69,700 |
def before_unlocking_fail(actor, x, ctxt) :
"""Unlocking requires a key."""
raise AbortAction(str_with_objs("{Bob} {needs} to be unlocking that with a key.", x=x), actor=actor) | 69,701 |
def test_token(current_user: User = Depends(get_current_user)):
"""
Test access token
"""
return current_user | 69,702 |
def image_ref(conn, id_, required=True):
"""Create reference dict for Image identified by ID `id_`. Use
OpenStack SDK connection `conn` to fetch the info. If `required`,
ensure the fetch is successful.
Returns: the ref dict, or None if not found and not `required`
Raises: openstack's ResourceNotFo... | 69,703 |
def get_host_ip():
# https://www.cnblogs.com/z-x-y/p/9529930.html
"""查询本机ip地址
用于快速获取主机的IP地址
Returns:
一个字符串,表示IP地址
例如:
127.0.0.1
"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockn... | 69,704 |
def get_test_nuplan_db_path() -> str:
"""Get a single nuPlan DB path to be used in testing."""
paths = discover_log_dbs(NUPLAN_DB_FILES)
return cast(str, paths[DEFAULT_TEST_DB_INDEX]) | 69,705 |
def optimize_unnamed_groups(exp):
"""return an equivalent expression tree but without unnamed groups
WARNING: has side-effect
"""
optimize_unnamed_groups_recursive(exp)
return skip_empty_group(exp) | 69,706 |
def parse(handle, pdbid, verbose=False):
"""Creates :class:`pdb_eda.ccp4.DensityMatrix` object.
:param handle: an I/O handle for .ccp4 file.
:type handle: :class:`io.IOBase`
:param pdbid: PDB entry ID.
:type pdbid: :py:class:`str`
:param verbose: verbose mode, defaults to :py:obj:`False`
:t... | 69,707 |
def _print_fails(path_list):
"""Format notebooks that failed lint and print to console.
Args:
path_list: A list of Path objects.
"""
template = textwrap.dedent("""\
The following notebook{plural} failed lint:
{filepaths}""")
paths = "\n".join([f" {str(fp)}" for fp in path_list])
plural = "s" if... | 69,708 |
def plot_set_3d(set_data, show_vertices=False, show_points=False,
show_shape=True, full_page=False, scale=0.7, show_axes=True,
only_hull_points=True):
"""
This function plots a three dimensional convex set.
:param set_data: The set to illustrate.
:param show_vertices: Show the vertices ... | 69,709 |
def include_container(container, args):
"""
Return truthy if container should be removed.
"""
inspect_data = inspect_container(container, args)
status = inspect_data["State"]["Status"]
# Note that while a timedelta of zero is a valid value for the created/exited/dead fields,
# it evaluates ... | 69,710 |
def split_line(is_splitline_show=True, **kwargs):
"""
:param is_splitline_show:
是否显示分割线
:param kwargs:
:return:
"""
_split_line = {
"show": is_splitline_show,
"lineStyle": line_style(**kwargs)
}
return _split_line | 69,711 |
def strToNMSLIBVect(text):
"""Converts to a string that can be fed to NMSLIB"""
return toksToStr(unique(getTokenIds(text))) | 69,712 |
def load_json(filepath):
"""Return parsed json file as dictionary."""
with open(filepath) as json_file:
try:
json_data = json.load(json_file)
except json.JSONDecodeError:
return None
return json_data | 69,713 |
def lighten(color, scale=1.0):
"""
Lighten a color.
- color is a tuple (r, g, b, a)
- scale can be any number, if < 1, color will be darken
"""
return tuple(map(
lambda x: int(min(max(x * scale, 0), 255)),
color[:3]
)) + color[3:] | 69,714 |
def fwhm(sigma=1.0):
"""
Get the Full-width-half-maximum value from the sigma value (~2.3548)
:param sigma: float, the sigma, default value is 1.0 (normalised gaussian)
:return: 2 * sqrt(2 * log(2)) * sigma = 2.3548200450309493 * sigma
"""
return 2 * np.sqrt(2 * np.log(2)) * sigma | 69,715 |
def com_google_fonts_check_105(font_metadata, canonical_filename):
"""METADATA.pb: Filename is set canonically?"""
if canonical_filename != font_metadata.filename:
yield FAIL, ("METADATA.pb: filename field (\"{}\")"
" does not match "
"canonical name \"{}\".".format(font_metada... | 69,716 |
def AB2Jy(ABmag):
"""Convert AB magnitudes to Jansky"""
return 10.**(-0.4*(ABmag+48.60))/1e-23 | 69,717 |
def course_details(request, course_id=None):
"""
Details about a course
"""
context = {}
# pylint: disable=E1101
course_detail = Course.objects.get(id=course_id)
course_user_list = (CourseUser.objects.filter(course=course_id)
.values_list('user', flat=True))
user_... | 69,718 |
def all_valid(formsets):
"""Validate every formset and return True if all are valid."""
# List comprehension ensures is_valid() is called for all formsets.
return all([formset.is_valid() for formset in formsets]) | 69,719 |
def test_camera_association_on_init():
"""
Test association of Focuser with Camera during Focuser init
"""
sim_camera = Camera()
focuser = SimFocuser(camera=sim_camera)
assert focuser.camera is sim_camera | 69,720 |
def get_links():
"""
Scrapes the links from the DATASET_LIST_URL and
returns a list of them.
"""
res = requests.get(DATASET_LIST_URL)
soup = BeautifulSoup(res.content, 'html.parser')
links = soup.find_all('a', text='CSV')
return [link['href'] for link in links] | 69,721 |
def horizontal_link_count(shape):
"""Number of horizontal links."""
assert len(shape) == 2
return shape[0] * (shape[1] - 1) | 69,722 |
def greedy_value(I: list, w: list, v: list, K: int) -> tuple:
"""
Solve knapsack problem with value greedness.
Takes most valuable first.
Parameters:
-----------
- I : items
- w : items' weights
- v : items' value
- K : knapsack size
Result:
... | 69,723 |
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_put(uuid, tapi_common_bandwidth_profile=None): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_put
creates or updates tapi.common.BandwidthProfile... | 69,724 |
def convert_datetime_decimal_day(dt_list):
""" returns the decimal day number for each datetime object in dt_list
:param dt_list: list of datetime objects to evaluate
:return: numpy array of the decimal day for each datetime
"""
timestamp = np.zeros(len(dt_list))
for i in range(len(dt_list)):
... | 69,725 |
def build_err_payload(aggregator, import_):
"""
Builds a JSON error response to return as a WS client notification.
"""
# flatten errors & warnings into a single list to send to the UI. Each ImportErrorSummary
# may optionally contain multiple related errors grouped by subcategory
errs = []
... | 69,726 |
def write_csv(starts, capacities, passengers):
"""
(int list, int list, (int list) list) -> None
Writes the required info of all trains to a csv file.
"""
stations = [[],[],[]]
#Creating the pass_i priority queues used in one_train
for i in range(3):
for j in range(len... | 69,727 |
def subscriber(pytestconfig) -> Optional[str]:
"""Subscriber of USS making UTM API calls"""
if pytestconfig.getoption(OPT_RID_AUTH):
session = make_session(pytestconfig, BASE_URL_RID, OPT_RID_AUTH)
session.get('/status', scope=rid.SCOPE_READ)
rid_sub = session.auth_adapter.get_sub()
if rid_sub:
... | 69,728 |
def create_bus(net, vn_kv, name=None, index=None, geodata=None, type="b",
zone=None, in_service=True, max_vm_pu=nan,
min_vm_pu=nan, coords=None, **kwargs):
"""
Adds one bus in table net["bus"].
Busses are the nodes of the network that all other elements connect to.
INPUT:... | 69,729 |
def m(x0: float, x1: float, y0: float, y1: float) -> float:
"""
Simple gradient function.
Parameters
----------
x0 : float
x co-ordinate at time 0.
x1 : float
x co-ordinate at time 1.
y0 : float
y co-ordinate at time 0.
y1 : float
y co-ordinate at time... | 69,730 |
def normalize(track_complex):
"""
Normalizes training data to use only amplitudes
"""
magnitude = np.abs(track_complex)
magnitude = np.reshape(magnitude, magnitude.shape + (1,))
return magnitude | 69,731 |
def get_child_watcher():
"""Equivalent to calling get_event_loop_policy().get_child_watcher()."""
return get_event_loop_policy().get_child_watcher() | 69,732 |
def ping_video_url(url):
""" Ping url """
try:
vs = cv2.VideoCapture(url)
flag, _ = vs.read()
except Exception as e:
logger.info("Exception in ping url: {}".format(e))
return flag | 69,733 |
def md_alignment(alignment):
"""Given alignment option, return corresponding markdown"""
if alignment == "<":
return ":", "-"
elif alignment == ">":
return "-", ":"
else:
return "-", "-" | 69,734 |
def password_from_sentence(sentence):
""" Create a phrase-based password.
Remember the sentence to remember the password.
The first letters of each word are added to the password,
numbers and special characters are kept as is.
Arguments:
sentence -- The sentence for create the passord (str)... | 69,735 |
def fltrust(gradients, net, lr, f, byz):
"""
gradients: list of gradients. The last one is the server update.
net: model parameters.
lr: learning rate.
f: number of malicious clients. The first f clients are malicious.
byz: attack type.
"""
param_list = [nd.concat(*[xx.reshape((-1, 1)) ... | 69,736 |
def print_verbose(result, test_output, level):
"""
Controls printing according to verbose level
Verbose level:
0: doesn't print anything
1: prints result and test_output when test has failed
2: always prints result and test_outputs
:param str result: output from a program
:... | 69,737 |
async def export_all_data(background_tasks: BackgroundTasks):
"""
Returns a zip file containing the csv files for all cameras and areas
"""
# TODO: Improve this function
cameras = [(section_dict["Id"], section_dict["Name"]) for section_dict in extract_config("cameras").values()]
areas = [(sectio... | 69,738 |
def humanized_model_to_dict(instance, readonly_fields, fields=None, exclude=None):
"""
Returns a dict containing the humanized data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will b... | 69,739 |
def save_model(model, model_name: str) -> str:
"""
Serves for saving pre-trained models to disk. Takes <model, model_name> as input (the name of the
saved model - can be with or without file extension).
Raises Exception if the model cannot be saved to disk.
"""
model_path = get_model_path(model_... | 69,740 |
def _refresh(fn):
"""Decorator to refresh the attributes of this object from the cluster"""
def wrapper(self, *args, **kwargs):
self.Refresh()
fn(self, *args, **kwargs)
self.Refresh()
return wrapper | 69,741 |
def define_haystack_units() -> UnitRegistry:
"""
Missing units found in project-haystack
Added to the registry
"""
unit_ureg = UnitRegistry(on_redefinition='ignore')
unit_ureg.define('% = [] = percent')
unit_ureg.define('pixel = [] = px = dot = picture_element = pel')
unit_ureg.define('d... | 69,742 |
def singlediode_voc(effective_irradiance, temp_cell, module_parameters):
"""
Calculate voc using the singlediode model.
Parameters
----------
effective_irradiance
temp_cell
module_parameters
Returns
-------
"""
photocurrent, saturation_current, resistance_series, resistan... | 69,743 |
def scans_generator(scans_train_directory_path: Path, scans_val_directory_path: Path, batch_size=16,
target_size=(256, 256), shuffle=True, backbone="efficientnetb0"):
"""
Tensorflow dataset generator.
:param scans_train_directory_path: It should contain one subdirectory per class. Any P... | 69,744 |
def Nabla_discrete(k_space,s_space=None,kfield=None):
"""
This function returns the difference operator represented in Fourier
space.
"""
if(about.hermitianize.status):
print 'It is not recommended to calculate derivatives in'
print 'Fourier space while hermitianize is o... | 69,745 |
def _usa():
"""Returns a data frame of cumulative daily infections per state."""
df = pd.read_csv('../data/usa.csv', usecols=['date', 'state', 'positive'],
parse_dates=['date'])
df = df.rename(columns=dict(state='region', positive='cumulative'))
return df.dropna(subset=['cumulative'... | 69,746 |
def getDateRange(dt):
""" 获取时间戳范围
参数
--------------
dt: str
url请求中传递过来的date参数
返回值
--------------
turple
返回一对 (起始时间戳,终止时间戳)
"""
if dt == 'weekend':
startDT = "2017-03-25 00:00:00"
endDT = "2017-03-27 00:00:00"
elif dt == 'weekday':
startDT ... | 69,747 |
def generate_random_color():
"""
Generate random color.
"""
r = random.random()
g = random.random()
b = random.random()
return (r, g, b) | 69,748 |
def get_highest_in_hierarchy(nodes):
"""Return highest nodes in the hierarchy that are in the `nodes` list.
The "highest in hierarchy" are the nodes closest to world: top-most level.
Args:
nodes (list): The nodes in which find the highest in hierarchies.
Returns:
list: The highest nod... | 69,749 |
def get_host_finding_detail_command(client, args):
"""
Retrieve information about particular host finding based on host finding id.
:param client: object of client
:param args: Demisto arguments provided by the user
:return: command output
"""
client_detail = get_client_detail_from_context(... | 69,750 |
def MPC_GetRxGainExternalRx() -> int:
"""Gets current reception gain
Returns
-------
int
Reception gain (raw value)
"""
gain = c_uint32()
CTS3Exception._check_error(_MPuLib.MPC_GetRxGainExternalRx(
c_uint8(0),
byref(gain)))
return gain.value | 69,751 |
def tiwary_mmvt_model(tmpdir_factory, tiwary_mmvt_model_persistent):
"""
Create a copy of the model that is not persistent. But this at least
doesn't require us to generate an entirely new model
"""
tiwary_mmvt_model = copy.deepcopy(tiwary_mmvt_model_persistent)
return tiwary_mmvt_model | 69,752 |
def _get_disposable_app_filename(clientInfo):
"""
Get name of file used to store creds.
"""
return clientInfo.get('file', clientInfo['name'] + '.client_data.json') | 69,753 |
def voc_to_df(img_dir:str, ann_dir:str, save_path:Optional[str]=None, class_map:Optional[Dict[str,str]]=None, **kwargs) -> pd.DataFrame:
""" finished, checked,
pascal voc annotations (in xml format) to one DataFrame (csv file)
Parameters:
-----------
img_dir: str,
directory of the image fi... | 69,754 |
def _timestamp_from_record_tuple(record):
"""Extract timestamp from HBase tuple record
"""
return record[0]['timestamp'] | 69,755 |
def concretize_backward_bound(backward_linexp: LinearExpression,
act_bound: Bound) -> Bound:
"""Compute the value of a backward bound.
Args:
backward_linexp: Coefficients of linear functions defined over a layer.
act_bound: Bound on the activations of that layer.
Returns:
... | 69,756 |
def order_sell_stop_loss(symbol,quantity,stopPrice,timeInForce='gtc'):
"""Submits a stop order to be turned into a market order once a certain stop price is reached.
:param symbol: The stock ticker of the stock to sell.
:type symbol: str
:param quantity: The number of stocks to sell.
:type quantity... | 69,757 |
def downloadable(orderby=None, limitby=None):
"""Return list of downloadable books.
Args:
orderby: orderby expression, see select()
limitby: limitby expression, see seelct()
Returns:
Records instance representing list of Creator instances.
"""
db = current.app.db
querie... | 69,758 |
def kube_upgrade_download_images(token):
"""
Ask System Inventory to kube upgrade download images
"""
return _patch_kube_upgrade_state(token, "downloading-images") | 69,759 |
async def test_http_server_int(pool_http_2p: Tuple[Pool, Pool]) -> None:
"""
Tests asynchronous sending and receiving of an integer between two communication pools
:param pool_http_2p: collection of two communication pools
"""
pool_http_2p[0].asend("local1", 1234)
res = await pool_http_2p[1].re... | 69,760 |
def learningRealTimeAStar(problem, heuristic=nullHeuristic):
"""Execute a number of trials of LRTA* and return the best plan found."""
"*** YOUR CODE HERE ***"
util.raiseNotDefined()
# MAXTRIALS = ... | 69,761 |
def builtin_precision(n):
"""
Count the digits in an integer.
Count the significant figures of a floating point number.
"""
if isinstance(n, BInt):
ds = str(n).lstrip('-')
return BInt(len(ds))
elif isinstance(n, BFloat):
if cmath.isinf(n.value) or cmath.isnan(n.value):
return BInt(0)
ds = str(n).lstrip... | 69,762 |
def main():
""" Handler for the main (index) page """
if _SINGLE_PAGE_UI:
# Redirect to the single page UI
return redirect(url_for("page"))
user = current_user()
# Initial tab to show, if any
tab = request.args.get("tab", None)
uid = user.id()
# Create a Firebase token f... | 69,763 |
def integrate(n=1.0):
"""
integrate the Lane Emden equations, and return the solution as a dictionary
"""
if n > 4.99:
raise SystemExit('Error: integrate: choose n < 4.99.')
list_xi = []
list_theta = []
list_d_theta = []
# Initial Conditions
xi = 1e-6
theta = 1.0
d... | 69,764 |
def test_list_language_pattern_2_nistxml_sv_iv_list_language_pattern_3_5(mode, save_output, output_format):
"""
Type list/language is restricted by facet pattern with value
([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{3})*
([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{3})*
(... | 69,765 |
def purge_all_unused():
"""Remove all unused data blocks."""
counter = 0
# keep this order.
# as the lower things are contained in the higher ones..
counter += purge_block(bpy.data.objects)
counter += purge_block(bpy.data.meshes)
counter += purge_block(bpy.data.materials)
counter += purg... | 69,766 |
def test_schmertmann():
"""
Checks settlement value against that from HW#7 crib ENCN452 course 2013
"""
dry_unit_dry_weight = 18.0
length = 2.5
width = 2.5
depth = 0.8
phi = 0.0
cohesion = 20
unit_dry_weight = 17
sl = geofound.create_soil(phi, cohesion, unit_dry_weight)
f... | 69,767 |
def analyze_repex(nc_file_path):
""" Analyze RepEx simulation and return the free energy over time and the final free energy. """
from openmmtools.multistate import MultiStateReporter, MultiStateSamplerAnalyzer
from perses.analysis.utils import open_netcdf
reporter = MultiStateReporter(nc_file_pat... | 69,768 |
def get_url_params(url, encoding="utf-8"):
"""
get the main_part and query_part from a url
"""
frags = urllib.parse.urlparse(url, allow_fragments=True)
components = (frags.scheme, frags.netloc, frags.path, frags.params, "", "")
return urllib.parse.urlunparse(components), urllib.parse.parse_qs(fr... | 69,769 |
def add_lambda_permission(stack_name,targetGroupArn,priority):
"""
Arguments:
FunctionName - Lambda function name (String)
SourceArn - ARN of the target group (String)
"""
client = boto3.client('lambda')
response = client.add_permission(
Action='lambda:InvokeFunction... | 69,770 |
def get_direction_values() -> []:
""" Returns all payment directions as enum """
return [DIRECTION_IN, DIRECTION_OUT, DIRECTION_TRANSFER] | 69,771 |
def run_simulations_on_all_cores(
agent: agent_base.Agent, env_name: str, batch_size: int
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Run multiple simulations using the same agent on multiple cores to obtaine actions,
observations, and rewards.
"""
cores = get_cores()
steps_pe... | 69,772 |
def expected_svg(image: str) -> str:
"""Calculate expected SVG."""
return Scour().scour_string(image) | 69,773 |
def update_reminders():
"""
Called by scheduler every 10 seconds, to update reminders
:return:
None
"""
reminders = get_reminders()
eel.updateReminders(' ', 1)
for reminder in reminders:
eel.updateReminders(reminder, 0) | 69,774 |
def make_lint_report(nb_fpath):
"""Run the tutorial linter on a notebook and capture the output."""
cmdline = ["python", "ci/lint_tutorial.py", nb_fpath]
res = subprocess.run(cmdline, capture_output=True)
return res.stdout.decode() | 69,775 |
def generate_docs():
"""The main function."""
tree = read_xml()
# Create a simple list to capture all of the STIGs
stig_ids = []
# Create defaultdicts to hold information to build our table of
# contents files for sphinx.
all_deployer_notes = defaultdict(list)
severity = defaultdict(li... | 69,776 |
def get_valid_ip_address(ls):
"""
Question 7.10: Compute all valid IP addresses
from decimal string, given that
"""
ips = []
# loop over first ip packet
first_idx = 1
while first_idx < 4 and first_idx < len(ls):
second_idx = 1
while second_idx < 4 and \
fi... | 69,777 |
def lemma_details_internal(request):
"""
Render word-detail.html for a lemma. `index` view function renders a whole page that contains word-detail.html too.
This function, however, is used by javascript to dynamically replace the paradigm with the ones of different sizes.
`lemma-id` and `paradigm-size`... | 69,778 |
def exit_subprocess():
"""Use os._exit(0) to exit the current subprocess.
Otherwise, the test catches the SystemExit and continues executing
in parallel with the original test, so you wind up with an
exponential number of tests running concurrently.
"""
os._exit(0) | 69,779 |
def _pack_single_bin(
rect_dict: Dict[int, Tuple[Number, Number]],
aspect_ratio: Tuple[Number, Number],
max_size: Tuple[float, float],
sort_by_area: bool,
density: float,
precision: float,
) -> Tuple[Dict[int, Tuple[Number, Number, Number, Number]], Dict[Any, Any]]:
"""Packs a dict of rectan... | 69,780 |
def _execute_case(case):
"""Run a single PEtab test suite case"""
case = petabtests.test_id_str(case)
logger.info(f"Case {case}")
# case folder
case_dir = os.path.join(petabtests.CASES_DIR, case)
# load solution
solution = petabtests.load_solution(case, 'sbml')
gt_chi2 = solution[petab... | 69,781 |
def test_order_wrong_option_in_kwargs(df_categorical):
"""
Raise ValueError if the value supplied to the `order`
parameter in kwargs is not one of None, 'sort', or 'appearance'.
"""
with pytest.raises(ValueError):
df_categorical.encode_categorical(col1=({1, 2, 3, 3}, "sorted")) | 69,782 |
def train_and_test_model(Data, Craters, MP, i_MP):
"""Function that trains, tests and saves the model, printing out metrics
after each model.
Parameters
----------
Data : dict
Inputs and Target Moon data.
Craters : dict
Human-counted crater data.
MP : dict
Contains a... | 69,783 |
def device_list():
"""Return a list of devices."""
return IMPL.device_list() | 69,784 |
def getAvailableLanguages():
"""generates a list of locale names, plus their full localized language and country names.
@rtype: list of tuples
"""
#Make a list of all the locales found in NVDA's locale dir
l=[x for x in os.listdir('locale') if not x.startswith('.')]
l=[x for x in l if os.path.isfile('locale... | 69,785 |
def analyze(source_code):
""" Trace the source code for display in the browser.
:param source_code: Source code to trace.
:return: (tracing_report, output)
"""
tracer = TraceRunner()
tracer.standard_files.old_files['stderr'] = StringIO()
tracer.max_width = 200000
with replace_input(sour... | 69,786 |
def scrape_data_post(id, scan_list, section, elements_path, save_status, file_names):
"""Given some parameters, this function can scrap friends/photos/videos/about/posts(statuses) of a profile"""
page = []
folder = os.path.join(os.getcwd(), "Data")
data = []
if save_status == 4:
page.append(... | 69,787 |
def _padding_for_dimension(data, axis, pad_value):
"""Tile `pad_value` so it can be used to pad `data` at the given axis.
Returns a tensor `result` that has the same shape as `data` up to dimension
`axis`, but where each value `data[i0...iaxis]` is replaced by `pad_value`.
I.e., returns `result[i0...iaxis, j0.... | 69,788 |
def is_error_status(status):
"""Function that determines whether the RPC status is an error.
Args:
status: Initialized RpcStatus message to check for errors.
"""
status.check_initialized()
return RpcError.from_state(status.state) is not None | 69,789 |
def test_equal_graphs_serialize_the_same(random_graph: nx.DiGraph) -> None:
"""E.g. even if the edges are shuffled."""
nodes = list(random_graph.nodes)
edges = list(random_graph.edges)
shuffle(nodes)
shuffle(edges)
shuffled_graph = nx.DiGraph()
shuffled_graph.add_nodes_from(nodes)
shuff... | 69,790 |
def plot_train_test(train_errors, test_errors, alphas, nb_neurones):
"""
train_errors, test_errors and lambas should be list (of the same size) the respective train error and test error for a given lambda,
* lambda[0] = 1
* train_errors[0] = RMSE of a ridge regression on the train set
* test_errors[... | 69,791 |
def getOption(key: str) -> typing.Union[str, bool, None]:
"""Get the value of a CLI solution option. If not defined, will return `None`."""
return _solutionOptions.get(key, None) | 69,792 |
def primes(upto):
"""
Prime sieve below an <upto> value.
Copied from http://rebrained.com/?p=458
Parameters
----------
upto : int
Find all primes leq this limit.
"""
primes = np.arange(3, upto+1, 2)
isprime = np.ones((upto-1)/2, dtype=bool)
for factor in primes[:int(np... | 69,793 |
def generate_dhcp_host_reservations(
hosts: Iterable[Tuple[netaddr.EUI, netaddr.IPAddress, Optional[str]]],
) -> Iterable[str]:
"""Generate lines suitable for dnsmasq's ``--dhcp-hostsfile=`` option.
:param hosts: The MAC address-IP address pairs of the hosts
"""
for mac, ip, hostname in hosts:
... | 69,794 |
def _filter_heads(heads, heads_height, radius, polygon):
"""Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2
Parameters
----------
heads : list of shapely.geometry.Point instances
The heads to filter out (in raster coordinates).
heads_height : list
The heads al... | 69,795 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | 69,796 |
def grass_raster_r_in_gdal(grass, raster_path, output_nm, location="#"):
"""import dem to target location
Parameters
----------
Returns:
-------
"""
if location != "#":
grass.run_command(
"r.in.gdal",
input=raster_path,
output=output_nm,
... | 69,797 |
def test_get_sparse_segmentation_labels_image():
"""
Test for get_sparse_segmentation_labels_image that changes segmentation image into a 2D array with
segmentation categories set for corresponding pixels values
"""
void_color = [100, 100, 100]
indices_to_colors_map = {
1: [10, 20, 30]... | 69,798 |
def program_name(output_str):
""" Reads the program name from the output file string.
:param output_str: string of the program's output file
:type output_str: str
:rtype: str
"""
prog_string = _get_prog_string(output_str)
prog_name = prog_string.split(':')[1].strip()
prog_n... | 69,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.