content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_entry_values(): """Get entry values""" entry = {} for key, question in ENTRY_QUESTIONS.items(): input_type = int if key == "time" else str while True: print_title(MAIN_MENU[1].__doc__) print(question) user_input = validate(get_input(), input_type)...
6736ac24bbbe83a0dcbd7a43cd12a1c1b1acbdab
31,600
def _create_snapshot(provider_id, machine_uuid, skip_store, wait_spawning): """Create a snapshot. """ _retrieve_machine(provider_id, machine_uuid, skip_store) manager = _retrieve_manager(provider_id) return manager.create_snapshot(machine_uuid, wait_spawning)
0d35309341dd27cc41e713c4fd950fee735c866d
31,601
def get_masked_lm_output(bert_config, input_tensor, positions, label_ids, label_weights): """Get loss and log probs for the masked LM.""" input_tensor = gather_indexes(input_tensor, positions) with tf.variable_scope("cls/predictions"): # We apply one more non-linear transformation be...
7668ff4c4bd18cb14ff625dc0de593250cedb794
31,602
import torch def binary_classification_loss(logits, targets, reduction='mean'): """ Loss. :param logits: predicted classes :type logits: torch.autograd.Variable :param targets: target classes :type targets: torch.autograd.Variable :param reduction: reduction type :type reduction: str ...
507f3b076f6b59a8629bf02aa69ece05f5063f45
31,603
import os def setup_rezconfig_file(local_packages_folder, release_packages_path): """ Write a rezconfig.py file for packages folder settings and create an env var to let rez reading it """ rez_config_filename = os.path.join((os.path.split(local_packages_folder)[0]), "rezconfig.py") os.environ["RE...
96c4933a4a917f78e99b964d362e15e7c63abd6d
31,604
def transform_with(sample, transformers): """Transform a list of values using a list of functions. :param sample: list of values :param transformers: list of functions """ assert not isinstance(sample, dict) assert isinstance(sample, (tuple, list)) if transformers is None or len(transforme...
9a1d7741070b670e7bf8dbf88e8a23361521265f
31,605
def concat_eval(x, y): """ Helper function to calculate multiple evaluation metrics at once """ return { "recall": recall_score(x, y, average="macro", zero_division=0), "precision": precision_score(x, y, average="macro", zero_division=0), "f1_score": f1_score(x, y, average="macro...
5a0732ac5926173f12e3f0bd6d6e0ace653c7494
31,606
from typing import List def split_into_regions(arr: np.ndarray, mode=0) -> List[np.ndarray]: """ Splits an array into its coherent regions. :param mode: 0 for orthogonal connection, 1 for full connection :param arr: Numpy array with shape [W, H] :return: A list with length #NumberOfRegions of arr...
59e46f5877f3f4fd12a918e9aa26a67a92eb4d5b
31,607
def register_model(model_uri, name): """ Create a new model version in model registry for the model files specified by ``model_uri``. Note that this method assumes the model registry backend URI is the same as that of the tracking backend. :param model_uri: URI referring to the MLmodel directory. Us...
7dcdaa54717e6e0ea45390a5af48b1e350574d12
31,608
def noreplace(f): """Method decorator to indicate that a method definition shall silently be ignored if it already exists in the full class.""" f.__noreplace = True return f
88b6e8fdf7064ed04d9a0c310bcf1717e05e7fa8
31,609
def position_encoding(length, depth, min_timescale=1, max_timescale=1e4): """ Create Tensor of sinusoids of different frequencies. Args: length (int): Length of the Tensor to create, i.e. Number of steps. depth (int): Dimensions of embedding. ...
9d8c9082d82fd41ea6b6655a50b3e802a12f6694
31,610
def perform_exchange(ctx): """ Attempt to exchange attached NEO for tokens :param ctx:GetContext() used to access contract storage :return:bool Whether the exchange was successful """ attachments = get_asset_attachments() # [receiver, sender, neo, gas] address = attachments[1] neo_amo...
6c2f01a27b40a284e89da1e84de696baa1464e1d
31,611
def Pose_2_Staubli_v2(H): """Converts a pose to a Staubli target target""" x = H[0,3] y = H[1,3] z = H[2,3] a = H[0,0] b = H[0,1] c = H[0,2] d = H[1,2] e = H[2,2] if c > (1.0 - 1e-10): ry1 = pi/2 rx1 = 0 rz1 = atan2(H[1,0],H[1,1]) elif c < (-1.0 + 1e-1...
9fae83e10df544b7d2c096c7a59aca60567de538
31,612
def create_gru_model(fingerprint_input, model_settings, model_size_info, is_training): """Builds a model with multi-layer GRUs model_size_info: [number of GRU layers, number of GRU cells per layer] Optionally, the bi-directional GRUs and/or GRU with layer-normalization can be explored...
222581216edaf6225fabe850d977d14955c66c6e
31,613
def convergence_rates(N, solver_function, num_periods=8): """ Returns N-1 empirical estimates of the convergence rate based on N simulations, where the time step is halved for each simulation. solver_function(I, V, F, c, m, dt, T, damping) solves each problem, where T is based on simulation for ...
e66b4395557e0a254636546555d87716e4b0cc50
31,614
import cProfile import io import pstats def profile(fnc): """A decorator that uses cProfile to profile a function""" def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = fnc(*args, **kwargs) pr.disable() s = io.StringIO() s...
9b5d248e2bd13d792e7c3cce646aa4c0432af8db
31,615
def _decode(y_pred, input_length, greedy=True, beam_width=100, top_paths=1): """Decodes the output of a softmax. Can use either greedy search (also known as best path) or a constrained dictionary search. # Arguments y_pred: tensor `(samples, time_steps, num_categories)` containing th...
7a73aa329245136ae560e92ebe67d997e57557f9
31,616
def rand_xyz_box(image_arrays, label, n, depth, img_size): """Returns n number of randomly chosen box. Args: image_arrays: 3D np array of images. label: label of images. normally is A or V n: number of random boxes generated from this function. depth : number of slices in Z...
3127522a7d08b5694fc92ab058736db1d7471676
31,617
def pageviews_by_document(start_date, end_date, verbose=False): """Return the number of pageviews by document in a given date range. * Only returns en-US documents for now since that's what we did with webtrends. Returns a dict with pageviews for each document: {<document_id>: <pageviews>, ...
c1a2c4ba2711803ca4b5e0cb8959a99b36f928ec
31,618
from re import T def format_time_string(seconds): """ Return a formatted and translated time string """ def unit(single, n): # Seconds and minutes are special due to historical reasons if single == "minute" or (single == "second" and n == 1): single = single[:3] if n == 1:...
27e0a084165605aa4b1a2b42c87840439686c255
31,619
import torch def warp_grid(flow: Tensor) -> Tensor: """Creates a warping grid from a given optical flow map. The warping grid determines the coordinates of the source pixels from which to take the color when inverse warping. Args: flow: optical flow tensor of shape (B, H, W, 2). The flow values ...
21f5765603f8fb42d5fe70668ab6d52b60c16bfe
31,620
def FORMULATEXT(*args) -> Function: """ Returns the formula as a string. Learn more: https//support.google.com/docs/answer/9365792. """ return Function("FORMULATEXT", args)
17cb21ee8b36439395b64fd410006ff03db7fedc
31,621
def photometer_and_plot(kicid, quarter, fake=False, makeplots=True, k2=False): """ ## inputs: - `kicid` - KIC number - `quarter` - Kepler observing quarter (or really place in list of files) ## outputs: - [some plots] - `time` - times in KBJD - `sap_photometry` - home-built SAP equivale...
84dc5131317c85a5bb9be6928da53ca5af1ae76b
31,622
def num_prim_vertices(prim: hou.Prim) -> int: """Get the number of vertices belonging to the primitive. :param prim: The primitive to get the vertex count of. :return: The vertex count. """ return prim.intrinsicValue("vertexcount")
298a4a67133fc857c129b922f7f5a0f21d6d0b40
31,623
def read_geoparquet(path: str) -> GeoDataFrame: """ Given the path to a parquet file, construct a geopandas GeoDataFrame by: - loading the file as a pyarrow table - reading the geometry column name and CRS from the metadata - deserialising WKB into shapely geometries """ # read parquet file ...
0fddb5452010e5d4546b3b34e7afae93698cd953
31,624
def cmd_run_json_block_file(file): """`file` is a file containing a FullBlock in JSON format""" return run_json_block_file(file)
594e10a7ef4e20b130a5b39c22a834208df846a6
31,625
def collide_mask(left, right): """collision detection between two sprites, using masks. pygame.sprite.collide_mask(SpriteLeft, SpriteRight): bool Tests for collision between two sprites by testing if their bitmasks overlap. If the sprites have a "mask" attribute, that is used as the mask; otherwis...
fcb309e0c5ca7bc59e5b39b8fd67a45a5281d262
31,626
import requests def fetch_production(zone_key='IN-GJ', session=None, target_datetime=None, logger=getLogger('IN-GJ')) -> list: """Requests the last known production mix (in MW) of a given country.""" session = session or requests.session() if target_datetime: raise NotImplemen...
e23e409d24349e998eb9c261805a050de12ed30c
31,627
def xyz_order(coordsys, name2xyz=None): """ Vector of orders for sorting coordsys axes in xyz first order Parameters ---------- coordsys : ``CoordinateSystem`` instance name2xyz : None or mapping Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or raises a KeyError ...
983c7adc5df8f54ecc92423eed0cd744971d4ec3
31,628
def parse_item(year, draft_type, row): """Parses the given row out into a DraftPick item.""" draft_round = parse_int(row, 'th[data-stat="draft_round"]::text', -1) draft_pick = parse_int(row, 'td[data-stat="draft_pick"]::text', -1) franchise = '/'.join( row.css('td[data-stat="team"] a::attr(href...
822a596e0c3e381658a853899920347b95a7ff59
31,629
def buildJointChain(prefix, suffix, startPos, endPos, jointNum, orientJoint="xyz", saoType="yup"): """ Build a straight joint chain defined by start and end position. :param prefix: `string` prefix string in joint name :param suffix: `string` suffix string in joint name :param startPos: `list` [x,y,...
fda63b96d2e5a1316fab9d2f9dc268ae0ff270d2
31,630
import time import torch def predict(model, img_load, resizeNum, is_silent, gpu=0): """ input: model: model img_load: A dict of image, which has two keys: 'img_ori' and 'img_data' the value of the key 'img_ori' means the original numpy array the value of the key 'img_data' is the list of five ...
04da68453aab79f732deb153cdcbed9ea267355c
31,631
def reverse_preorder(root): """ @ input: root of lcrs tree @ output: integer list of id's reverse preorder """ node_list = [] temp_stack = [root] while len(temp_stack) != 0: curr = temp_stack.pop() node_list.append(curr.value) if curr.child is not None: ...
06a53756db0f5c990537d02de4fcaa57cc93169d
31,632
import scipy def calc_binned_percentile(bin_edge,xaxis,data,per=75): """Calculate the percentile value of an array in some bins. per is the percentile at which to extract it. """ percen = np.zeros(np.size(bin_edge)-1) for i in xrange(0,np.size(bin_edge)-1): ind = np.where((xaxis > bin_edge[i])...
798cd1e4f1070b27766f2390442fa81dfad15aaa
31,633
def run_services(container_factory, config, make_cometd_server, waiter): """ Returns services runner """ def _run(service_class, responses): """ Run testing cometd server and example service with tested entrypoints Before run, the testing cometd server is preloaded with passed ...
df7d1c3fdf7e99ebf054cfc6881c8073c2cf4dee
31,634
import requests def cleaned_request(request_type, *args, **kwargs): """ Perform a cleaned requests request """ s = requests.Session() # this removes netrc checking s.trust_env = False return s.request(request_type, *args, **kwargs)
b6c99c85a64e5fd78cf10cc986c9a4b1542f47d3
31,635
from typing import List from typing import Set def construct_speech_to_text_phrases_context(event: EventIngestionModel) -> List[str]: """ Construct a list of phrases to use for Google Speech-to-Text speech adaption. See: https://cloud.google.com/speech-to-text/docs/speech-adaptation Parameters -...
e8834afd4e53d446f2dda1fd79383a0266010e5b
31,636
def data_science_community(articles, authors): """ Input: Articles and authors collections. You may use only one of them Output: 3-tuple reporting on subgraph of authors of data science articles and their co-authors: (number of connected components,size of largest connected component, size of smalle...
3a81fc7674a2d421ff4649759e61797a743b7aae
31,637
def breadth_first_search(G, seed): """Breadth First search of a graph. Parameters ---------- G : csr_matrix, csc_matrix A sparse NxN matrix where each nonzero entry G[i,j] is the distance between nodes i and j. seed : int Index of the seed location Returns ------- ...
047596e378f0496189f2e164e2b7ede4a6212f19
31,638
def main_page(): """ Pass table of latest sensor readings as context for main_page """ LOG.info("Main Page triggered") context = dict( sub_title="Latest readings:", table=recent_readings_as_html() ) return render_template('main_page.html', **context)
6c9ac7c3306eb10d03269ca4e0cbca9c68a19644
31,639
import yaml def load_config_file(filename): """Load configuration from YAML file.""" docs = yaml.load_all(open(filename, 'r'), Loader=yaml.SafeLoader) config_dict = dict() for doc in docs: for k, v in doc.items(): config_dict[k] = v return config_dict
d61bb86e605a1e744ce3f4cc03e866c61137835d
31,640
def CausalConv(x, dilation_rate, filters, kernel_size=2, scope = ""): """Performs causal dilated 1D convolutions. Args: x : Tensor of shape (batch_size, steps, input_dim). dilation_rate: Dilation rate of convolution. filters: Number of convolution filters. kernel_size: Width of convolution kernel. ...
08ffde5e4a9ae9ebdbb6ed83a22ee1987bf02b1e
31,641
import functools def makeTable(grid): """Create a REST table.""" def makeSeparator(num_cols, col_width, header_flag): if header_flag == 1: return num_cols * ("+" + (col_width) * "=") + "+\n" else: return num_cols * ("+" + (col_width) * "-") + "+\n" def normalizeCe...
c889a4cf505b5f0b3ef75656acb38f621c7fff31
31,642
from pathlib import Path import os import configparser import io def generate_and_validate(config: Config) -> str: """Validate and generate mypy config.""" config_path = config.root / ".strict-typing" with config_path.open() as fp: lines = fp.readlines() # Filter empty and commented lines. ...
b3c4a94aab6404f4ab88a8dc700cebd6a484a422
31,643
def coords_to_bin( x: npt.NDArray, y: npt.NDArray, x_bin_width: float, y_bin_width: float, ) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]]: """ x: list of positive east-west coordinates of some sort y: list of positive north-south coordinates of some sort x_bin_width: bin width fo...
874950836d6d03e1dc0f39bdb53653789fe64605
31,644
from typing import Callable def _gcs_request(func: Callable): """ Wrapper function for gcs requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except NotFound: ...
a57867df668eb9b139ee8e07a405868676c9e0f2
31,645
def nllsqfunc(params: np.ndarray, qm: HessianOutput, qm_hessian: np.ndarray, mol: Molecule, loss: list[float]=None) -> np.ndarray: """Residual function for non-linear least-squares optimization based on the difference of MD and QM hessians. Keyword arguments ----------------- para...
0debdca80de9e7ea136683de04bc838ceb2f42e2
31,646
import time def wait_for_mongod_shutdown(mongod_control, timeout=2 * ONE_HOUR_SECS): """Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1.""" start = time.time() status = mongod_control.status() while status != "stopped": if time.time() - start >= timeout: ...
837271069f8aa672372aec944abedbd44664a3d3
31,647
from typing import List import re def get_installed_antivirus_software() -> List[dict]: """ Not happy with it either. But yet here we are... Thanks Microsoft for not having SecurityCenter2 on WinServers So we need to detect used AV engines by checking what is installed and do "best guesses" This test ...
b122960b48edfb0e193c354293b28bc1ead0a936
31,648
def mi(x,y,k=3,base=2): """ Mutual information of x and y x,y should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]] if x is a one-dimensional scalar and we have four samples """ x = [[entry] for entry in x] y = [[entry] for entry in y] assert len(x)==len(y), "Lists should have ...
960501be5134dcfe99ca29b50622dbfc0b403b78
31,649
def _xls_cc_ir_impl_wrapper(ctx): """The implementation of the 'xls_cc_ir' rule. Wrapper for xls_cc_ir_impl. See: xls_cc_ir_impl. Args: ctx: The current rule's context object. Returns: ConvIRInfo provider DefaultInfo provider """ ir_conv_info, built_files, runfiles = _xls_cc...
c76bddc8b05322b2df4af67415f783aa1f2635bb
31,650
from typing import List from typing import Tuple from typing import DefaultDict def create_dataset(message_sizes: List[int], labels: List[int], window_size: int, num_samples: int, rand: np.random.RandomState) -> Tuple[np.ndarray, np.ndarray]: """ Creates the attack dataset by randomly sampling message sizes o...
081e0c6ddc18988d8e24a08ec4a4e565f318d23a
31,651
def infer_Tmap_from_clonal_info_alone_private( adata_orig, method="naive", clonal_time_points=None, selected_fates=None ): """ Compute transition map using only the lineage information. Here, we compute the transition map between neighboring time points. We simply average transitions across all cl...
9926e2a6faf50bed2d1668de031a600e0f65c1af
31,652
import math def percentile(seq: t.Iterable[float], percent: float) -> float: """ Find the percentile of a list of values. prometheus-client 0.6.0 doesn't support percentiles, so we use this implementation Stolen from https://github.com/heaviss/percentiles that was stolen from http://code.activesta...
640f132366bad8bf0c58aa318b5be60136925ab9
31,653
from typing import Union def select_view_by_cursors(**kwargs): """ Selects the Text View ( visible selection ) for the given cursors Keyword Args: sel (Tuple[XTextRange, XTextRange], XTextRange): selection as tuple of left and right range or as text range. o_doc (GenericTextDocument, opti...
42c42c4b60d802a66e942ac8fa8efe97a8253ea3
31,654
from typing import List from typing import Dict def load_types( directories: List[str], loads: LoadedFiles = DEFAULT_LOADS, ) -> Dict[str, dict]: """Load schema types and optionally register them.""" schema_data: Dict[str, dict] = {} # load raw data for directory in directories: load...
8dc1f3625c03451eb9ac28804715ccf260400536
31,655
def fit_circle(img, show_rect_or_cut='show'): """ fit an ellipse to the contour in the image and find the overlaying square. Either cut the center square or just plot the resulting square Code partly taken from here: https://stackoverflow.com/questions/55621959/opencv-fitting-a-single-circle-to-an-...
fdeb8f9a24159236609eac271016624f95f62504
31,656
from typing import Mapping from typing import Any from typing import MutableMapping def unflatten_dict( d: Mapping[str, Any], separator: str = '.', unflatten_list: bool = False, sort: bool = False ) -> MutableMapping[str, Any]: """ Example: In []: unflatten_dict({'count.chans.HU_SN': 10}) Out[]: {'count': {'...
40662a4884171c444ed40c654497f6a0e17a132d
31,657
def _xinf_1D(xdot,x0,args=(),xddot=None,xtol=1.49012e-8): """Private function for wrapping the solving for x_infinity for a variable x in 1 dimension""" try: if xddot is None: xinf_val = float(fsolve(xdot,x0,args,xtol=xtol)) else: xinf_val = float(newton_meth(xdot,x0,...
e69c08b914395d93a94544d9ba085a440951a03c
31,658
import types from typing import Dict import operator def to_bag_of_words( doclike: types.DocLike, *, by: TokenGroupByType = "lemma_", weighting: WeightingType = "count", **kwargs, ) -> Dict[int, int | float] | Dict[str, int | float]: """ Transform a ``Doc`` or ``Span`` into a bag-of-words:...
0065eba8ff7f74b420efc8c65688ab293dee1dda
31,659
def get_trip_info(origin, destination, date): """ Provides basic template for response, you can change as many things as you like. :param origin: from which airport your trip beings :param destination: where are you flying to :param date: when :return: """ template = { "kind": "q...
d1dfd35f41538e800b5c6f5986faac7fcd30ebf3
31,660
def serialise(data, data_type=None): """ Serialises the specified data. The result is a ``bytes`` object. The ``deserialise`` operation turns it back into a copy of the original object. :param data: The data that must be serialised. :param data_type: The type of data that will be provided. If no data type is pr...
6c4e7b144e3e938d30cceee5503290f8cf31ca27
31,661
from sys import prefix def localenv(*args, **kwargs): """Execute cmd in local environment.""" # Remove empty keys kwargs = {k: v for k, v in kwargs.items() if v} template_vars = { "root_path": ROOT_PATH, "environment": kwargs.pop("environment", DEFAULT_ENVIRONMENT), "config_f...
20a9326e0f9852eb83757655540925a83a9b3cff
31,662
def topopebreptool_RegularizeShells(*args): """ * Returns <False> if the shell is valid (the solid is a set of faces connexed by edges with connexity 2). Else, splits faces of the shell; <OldFacesnewFaces> describes (face, splits of face). :param aSolid: :type aSolid: TopoDS_Solid & :param OldSheNewS...
8aa44c5b79f98f06596a5e6d9db8a4cf18f7dad3
31,663
import threading from typing import Optional from typing import Callable def _cancel_task_if( logger: gluetool.log.ContextAdapter, cancel: threading.Event, undo: Optional[Callable[[], None]] = None ) -> bool: """ Check given cancellation event, and if it's set, call given (optional) undo callback....
0c553e8c9191fb8dffab5c34f18fac1302fa53bc
31,664
def empty_filter(item, *args, **kwargs): """ Placeholder function to pass along instead of filters """ return True
d72ac5a0f787557b78644bcedd75e71f92c38a0b
31,665
def Get_User_Tags(df, json_response, i, github_user): """ Calculate the tags for a user. """ all_repos_tags = pd.DataFrame(0, columns=df.columns, index=pyjq.all(".[] | .name", json_response)) num_repos = len(pyjq.all(".[] | .name", json_response)) # new_element = pd.DataFrame(0, np.zeros(...
80955e2794e9f9d4f65a3f048bc7dc0d450ebb3d
31,666
import ctypes def ssize(newsize, cell): """ Set the size (maximum cardinality) of a CSPICE cell of any data type. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ssize_c.html :param newsize: Size (maximum cardinality) of the cell. :type newsize: int :param cell: The cell. :type c...
52eb884e7477ddb98dc905ab848c61b83ac16123
31,667
from typing import Optional import os def env_interactive() -> Optional[bool]: """ Check the `GLOBUS_CLI_INTERACTIVE` environment variable for a boolean, and *let* `strtobool` raise a `ValueError` if it doesn't parse. """ explicit_val = os.getenv("GLOBUS_CLI_INTERACTIVE") if explicit_val is No...
ecdddad354757066fc2dde170a044b6462d9c78b
31,668
def extend_data(data, length, offset): """Extend data using a length and an offset.""" if length >= offset: new_data = data[-offset:] * (alignValue(length, offset) // offset) return data + new_data[:length] else: return data + data[-offset:-offset+length]
923372c1fde14335331eb38b40e118b426cc9219
31,669
def RAND_egd(path): # real signature unknown; restored from __doc__ """ RAND_egd(path) -> bytes Queries the entropy gather daemon (EGD) on the socket named by 'path'. Returns number of bytes read. Raises SSLError if connection to EGD fails or if it does not provide enough data to seed PRNG. ...
5ef4e3e065c44058996c1793541cd9f2a599b106
31,670
from typing import List from typing import Dict from typing import Any def get_types_map(types_array: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: """Get the type name of a metadata or a functionality.""" return {type_["name"]: type_ for type_ in types_array}
9354eff434b589a19360ee13d8bf7d9ab9e1002d
31,671
def update_flavor(request, **kwargs): """Update a flavor. """ data = request.DATA flavor_id = data['flavor']['id'] conn = _get_sdk_connection(request) flavor = conn.load_balancer.update_flavor( flavor_id, name=data['flavor'].get('name'), description=data['flavor'].get('...
9f165df73f3c557956d466e3fec6d720a1ee76cb
31,672
from typing import List import re async def get_all_product_features_from_cluster() -> List[str]: """ Returns a list of all product.feature in the cluster. """ show_lic_output = await scontrol_show_lic() PRODUCT_FEATURE = r"LicenseName=(?P<product>[a-zA-Z0-9_]+)[_\-.](?P<feature>\w+)" RX_PROD...
9822c952654b3e2516e0ec3b5cf397ced8b3eaaf
31,673
def call_status(): """ 入浴状態を取得 入浴前:0 入浴中:1 入浴後:2 :return: """ user_id = "testuser" result_dict = check_status(user_id) return jsonify(result_dict)
9ef37eeb309c64cb7b4759323b4cb9569b910c65
31,674
def dice_loss(pred, target, smooth=1.): """Dice loss """ pred = pred.contiguous() target = target.contiguous() intersection = (pred * target).sum(dim=2).sum(dim=2) loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth))) return los...
5879769ac379395e35f9accda9d917094aa07301
31,675
def _get_scope_contacts_by_object_id(connection, object_id, object_type, scope_contact_type): """Gets scope contacts by object id. Args: connection: Database connection. object_id: An integer value of scope object id. object_type: A string value of scope object type...
c7c1fe05cb48fb5e28499f995a8c606c9e421d6e
31,676
import re def remove_mentions(text): """Remove @-mentions from the text""" return re.sub('@\w+', '', text)
5cbdd40a602f24f8274369e92f9159cbb2f6a230
31,677
def put_thread(req_thread: ReqThreadPut): """Put thread for video to DynamoDB""" input = create_update_item_input(req_thread) try: res = client.update_item(**input) return res except ClientError as err: err_message = err.response["Error"]["Message"] raise HTTPException(...
733370296c022a985b49193a1b528e0df8271624
31,678
from admin.admin_blueprint import admin_blueprint from questionnaire.questionnaire_blueprint import questionnaire_blueprint from user.user_blueprint import user_blueprint def create_app(config_name: str): """Application factory Args: config_name (str): the application config name to determine which e...
13e171d780f87ffad0802703ab72483669bc3453
31,679
import numpy def get_clean_num(num): """ Get the closest clean number match to num with bases 1, 2, 5. Args: num: the number Returns: the closest number """ if num == 0: return 0 sign = num > 0 and 1 or -1 exp = get_exp(num) nums = numpy.array((1, 2, 5, 10))*(10**...
09b4f5893e8d33a16217a2292ca75d7730e5d90e
31,680
def with_config_error(func): """Add config error context.""" @wraps(func) def wrapper(*args, **kwargs): with config_key_error(): return func(*args, **kwargs) return wrapper
667ab25648c17d087fbc54fd9d284c98c40b4b0b
31,681
def _flat(l): """Flattens a list. """ f = [] for x in l: f += x return f
9b2e432d79f08840d417601ff950ff9fa28073ef
31,682
def axesDict(T_axes): """Check connectivity based on Interval Vectors.""" intervalList = [ T_axes[0], T_axes[1], T_axes[2], (12 - T_axes[0]), (12 - T_axes[1]), (12 - T_axes[2])] return intervalList
6b1e8c59d12a3c2c548b95f3bcd8d7a3de4ef931
31,683
def _settings_to_component( name: str, settings: configuration.ProjectSettings, options: amos.Catalog) -> bases.Projectbases.Component: """[summary] Args: name (str): [description] settings (configuration.ProjectSettings): [description] options (amos.Catalog): [description]...
7e709a27b275587ce742c08d10efbd7b0aa171ce
31,684
import ipdb import tqdm def iss(data, gamma21, gamma32, KDTree_radius, NMS_radius, max_num=100): """ Description: intrinsic shape signatures algorithm based on cuda FRNN and cuda maximum suppression Args: data: numpy array of point cloud, shape(num_points, 3) gamma21: gamma32: ...
bf2b84ed179314334a6e7a88f84f6f86468006dd
31,685
import os import aiohttp import traceback import sys async def main(request): """Handle requests.""" try: # Get payload payload = await request.read() # Get authentication secret = os.environ.get("GH_SECRET") token = os.environ.get("GH_AUTH") bot = os.environ....
c2148bc11e12b241c0f6984a9e3f140a8f5799cf
31,686
from green.version import pretty_version import copy import configparser import sys import logging import os import tempfile def mergeConfig(args, testing=False): # pragma: no cover """ I take in a namespace created by the ArgumentParser in cmdline.main() and merge in options from configuration files. T...
73f057adead67d4cdaa7d06f19ee72ffe8f9bb91
31,687
import requests def login_wechat(): """ This api logins a user through wechat app. """ code = request.json.get('code', None) wechat_code2session_url = 'https://api.weixin.qq.com/sns/jscode2session' payload = { 'appid': current_app.config['WECHAT_APPID'], 'secret': current_app....
985eddbcb39ade8aebad3d9d179a0b174df50280
31,688
def is_no_entitled(request): """Check condition for needing to entitled user.""" no_entitled_list = ["source-status"] no_auth = any(no_auth_path in request.path for no_auth_path in no_entitled_list) return no_auth
feee0962568b20c685fd85096ce00dbb91b91fe5
31,689
def _make_selector_from_key_distribution_options( options) -> reverb_types.SelectorType: """Returns a Selector from its KeyDistributionOptions description.""" one_of = options.WhichOneof('distribution') if one_of == 'fifo': return item_selectors.Fifo() if one_of == 'uniform': return item_selectors.U...
3b932328f7b3e226e3dada54c8f1ca08e32167af
31,690
import base64 def json_numpy_obj_hook(dct): """ Decodes a previously encoded numpy ndarray with proper shape and dtype from: http://stackoverflow.com/a/27948073/5768001 :param dct: (dict) json encoded ndarray :return: (ndarray) if input was an encoded ndarray """ if isinstance(dct, dic...
50aab4855d63206534981bce95ec0219dec9724e
31,691
from typing import Optional import copy def redirect_edge(state: SDFGState, edge: graph.MultiConnectorEdge[Memlet], new_src: Optional[nodes.Node] = None, new_dst: Optional[nodes.Node] = None, new_src_conn: Optional[str] = None, ...
368ff8dace5b781d05f7e75fe9d57cae648aee9d
31,692
def svn_fs_lock(*args): """ svn_fs_lock(svn_fs_t fs, char path, char token, char comment, svn_boolean_t is_dav_comment, apr_time_t expiration_date, svn_revnum_t current_rev, svn_boolean_t steal_lock, apr_pool_t pool) -> svn_error_t """ return _fs.svn_fs_lock(*args)
f711b280a24f5d3c595a81013d1dc5275a997a60
31,693
def maybe_double_last(hand): """ :param hand: list - cards in hand. :return: list - hand with Jacks (if present) value doubled. """ if hand[-1] == 11: hand[-1] = 22 return hand
378546e8dd650a67a5d9d9eed490969fd085bfb1
31,694
def length(draw, min_value=0, max_value=None): """Generates the length for Blast+6 file format. Arguments: - `min_value`: Minimum value of length to generate. - `max_value`: Maximum value of length to generate. """ return draw(integers(min_value=min_value, max_value=max_value))
e3ac6b5d9bcc6380e475785047438b3be8a81288
31,695
def ppw(text): """PPW -- Percentage of Polysyllabic Words.""" ppw = None polysyllabic_words_num = 0 words_num, words = word_counter(text, 'en') for word in words: if syllable_counter(word) >= 3: polysyllabic_words_num += 1 if words_num != 0: ppw = polysyllabic_words...
b8c8c92a4947404a7166e63458e7d4eb2f9a00fc
31,696
def is_running_in_azure_ml(aml_run: Run = RUN_CONTEXT) -> bool: """ Returns True if the given run is inside of an AzureML machine, or False if it is on a machine outside AzureML. When called without arguments, this functions returns True if the present code is running in AzureML. Note that in runs with ...
3d2d6bcf95c34def5fff9c8bf1053c785b075895
31,697
def format_test_case(test_case): """Format test case from `-[TestClass TestMethod]` to `TestClass_TestMethod`. Args: test_case: (basestring) Test case id in format `-[TestClass TestMethod]` or `[TestClass/TestMethod]` Returns: (str) Test case id in format TestClass/TestMethod. """ tes...
f2d4530fbcc9d07409bfc7a88225653a7f550185
31,698
def _truncate_seed(seed): """ Truncate the seed with MAXINT32. Args: seed (int): The seed to be truncated. Returns: Integer. The seed with MAXINT32. """ return seed % _MAXINT32
2caf14236ec1697d6ab7144604e0f2be05d525d2
31,699