content
stringlengths
22
815k
id
int64
0
4.91M
def get_rectangle(roi): """ Get the rectangle that has changing colors in the roi. Returns boolean success value and the four rectangle points in the image """ gaussian = cv2.GaussianBlur(roi, (9, 9), 10.0) roi = cv2.addWeighted(roi, 1.5, gaussian, -0.5, 0, roi) nh, nw, r = roi.shape ...
27,800
async def challenge_process_fixture() -> Challenge: """ Populate challenge with: - Default user - Is open - Challenge in process """ return await populate_challenge()
27,801
def _read_pdg_masswidth(filename): """Read the PDG mass and width table and return a dictionary. Parameters ---------- filname : string Path to the PDG data file, e.g. 'data/pdg/mass_width_2015.mcd' Returns ------- particles : dict A dictionary where the keys are the partic...
27,802
def fps_and_pred(model, batch, **kwargs): """ Get fingeprints and predictions from the model. Args: model (nff.nn.models): original NFF model loaded batch (dict): batch of data Returns: results (dict): model predictions and its predicted fingerprints, conformer weights, etc. ...
27,803
def preprocess_text(text): """ Should return a list of words """ text = contract_words(text) text = text.lower() # text = text.replace('"', "").replace(",", "").replace("'", "") text = text.replace('"', "").replace(",", "").replace("'", "").replace(".", " .") ## added by PAVAN ## T...
27,804
def set_backend(name, unsafe=False): """ Set a specific backend by name Parameters ---------- name : str. unsafe : optional: bool. Default: False. If False, does not switch backend if current backend is not unified backend. """ if (backend.is_unified() == False and unsafe =...
27,805
def unicodeToAscii(s): """unicodeToAscii Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427 For example, 'Ślusàrski' -> 'Slusarski' """ return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' and c ...
27,806
def update_ip_table(nclicks, value): """ Function that updates the IP table in the Elasticsearch Database that contains the frequency as well as the IP address of the machine querying that particular domain. Args: nclicks: Contains the number of clicks registered by the submit button. ...
27,807
def collect_subclasses(mod, cls, exclude=None): """Collecting all subclasses of `cls` in the module `mod` @param mod: `ModuleType` The module to collect from. @param cls: `type` or (`list` of `type`) The parent class(es). @keyword exclude: (`list` of `type`) Classes to not include. """ out = []...
27,808
def download_file( sample_id, file_type, destination, host, email, password, api_key, no_progress, ): # noqa: D413,D301,D412 # pylint: disable=C0301 """Download sample file metadata. SAMPLE_ID specific sample for which to download the results FILE_TYPE specific deliver...
27,809
def check_collections_equivalent(a: typing.Collection, b: typing.Collection, allow_duplicates: bool = False, element_converter: typing.Callable = identity) -> typing.Tuple[str, list]: """ :param a: one collection to compare :param b: other c...
27,810
def voting_classifier(*args, **kwargs): """ same as in gradient_boosting_from_scratch() """ return VotingClassifier(*args, **kwargs)
27,811
def download_vctk(destination, tmp_dir=None, device="cpu"): """Download dataset and perform resample to 16000 Hz. Arguments --------- destination : str Place to put final zipped dataset. tmp_dir : str Location to store temporary files. Will use `tempfile` if not provided. ...
27,812
def assert_allclose(actual: float, desired: int): """ usage.scipy: 5 usage.sklearn: 1 usage.statsmodels: 1 """ ...
27,813
def replace_subject_with_object(sent, sub, obj): """Replace the subject with object and remove the original subject""" sent = re.sub(r'{}'.format(obj), r'', sent, re.IGNORECASE) sent = re.sub(r'{}'.format(sub), r'{} '.format(obj), sent, re.IGNORECASE) return re.sub(r'{\s{2,}', r' ', sent, re.IGNOREC...
27,814
def estimate_using_user_recent(list_type: str, username: str) -> int: """ Estimate the page number of a missing (entry which was just approved) entry and choose the max page number this requests a recent user's list, and uses checks if there are any ids in that list which arent in the approved cach...
27,815
def git_acquire_lock(lock_path, log_file=None): """ >>> import os >>> lock_test = '/tmp/lock-test' >>> git_acquire_lock(lock_test) >>> os.path.exists(lock_test) True >>> os.rmdir(lock_test) """ locked = False attempt = 1 while not locked: try: # 600 attemp...
27,816
def codegen_reload_data(): """Parameters to codegen used to generate the fn_html2pdf package""" reload_params = {"package": u"fn_html2pdf", "incident_fields": [], "action_fields": [], "function_params": [u"html2pdf_data", u"html2pdf_data_type", u"htm...
27,817
def set_default_parameter(self, parameter_name, parameter_value): """ Sets a parameters to be used as default (template) in the handling of a request. :type parameter_name: String :param parameter_name: The name of the parameter to be set. :type parameter_value: Object :param parame...
27,818
def instrument_keywords(instrument, caom=False): """Get the keywords for a given instrument service Parameters ---------- instrument: str The instrument name, i.e. one of ['niriss','nircam','nirspec', 'miri','fgs'] caom: bool Query CAOM service Returns ------- p...
27,819
def header_info(data_type, payload): """Report additional non-payload in network binary data. These can be status, time, grapic or control structures""" # Structures are defined in db_access.h. if payload == None: return "" from struct import unpack data_type = type_name(data_type) ...
27,820
def dsa_verify(message, public, signature, constants=None): """Checks if the signature (r, s) is correct""" r, s = signature p, q, g = get_dsa_constants(constants) if r <= 0 or r >= q or s <= 0 or s >= q: return False w = inverse_mod(s, q) u1 = (bytes_to_num(sha1_hash(message)) * w) % q...
27,821
def set_up_cgi(): """ Return a configured instance of the CGI simulator on RST. Sets up the Lyot stop and filter from the configfile, turns off science instrument (SI) internal WFE, and reads the FPM setting from the configfile. :return: CGI instrument instance """ webbpsf.setup_logging('ER...
27,822
def plot_line( timstof_data, # alphatims.bruker.TimsTOF object selected_indices: np.ndarray, x_axis_label: str, colorscale_qualitative: str, title: str = "", y_axis_label: str = "intensity", remove_zeros: bool = False, trim: bool = True, height: int = 400 ) -> go.Figure: """Plot...
27,823
def _ascii_encode(data: str, errors: str, index: int, out: bytearray): """Tries to encode `data`, starting from `index`, into the `out` bytearray. If it encounters any codepoints above 127, it tries using the `errors` error handler to fix it internally, but returns the a tuple of the first and last inde...
27,824
def all_gather(data): """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = get_world_size() if world_size == 1: return [data] data_list ...
27,825
def get_title_count(titles, is_folder): """ Gets the final title count """ final_title_count = 0 if len(titles.all) == 0: if is_folder == False: sys.exit() else: return 0 else: for group, disc_titles in titles.all.items(): for title i...
27,826
def draw_graph( adata, layout=None, color=None, alpha=None, groups=None, components=None, legend_loc='right margin', legend_fontsize=None, legend_fontweight=None, color_map=None, palette=None, right_margin=None, size...
27,827
def post_token(): """ Receives authentication credentials in order to generate an access token to be used to access protected models. Tokens generated by this endpoint are JWT Tokens. """ # First we verify the request is an actual json request. If not, then we # responded with ...
27,828
def test_document_query(): # type: () -> None """ A realistic unit test demonstrating the usage of `DocumentQuery`. """ PRODUCTS_COLLECTION = [ # NOTE: use ordered dicts so that order of submitted metrics is deterministic on Python 2 too. OrderedDict( ( (...
27,829
def judgement(seed_a, seed_b): """Return amount of times last 16 binary digits of generators match.""" sample = 0 count = 0 while sample <= 40000000: new_a = seed_a * 16807 % 2147483647 new_b = seed_b * 48271 % 2147483647 bin_a = bin(new_a) bin_b = bin(new_b) la...
27,830
def GJK(shape1, shape2): """ Implementation of the GJK algorithm PARAMETERS ---------- shape{1, 2}: Shape RETURN ------ : bool Signifies if the given shapes intersect or not. """ # Initialize algorithm parameters direction = Vec(shape1.center, shape2....
27,831
def test_edit_add_one_author(user0, three_items_authors_only): """Adding one author works properly.""" for item in three_items_authors_only: common.add_item(item, user0) content = { "id": "1", "title": "Test", "authors": [ {"last_name": "Smith", "first_name": "J...
27,832
def _set_int_config_parameter(value: OZWValue, new_value: int) -> int: """Set a ValueType.INT config parameter.""" try: new_value = int(new_value) except ValueError as err: raise WrongTypeError( ( f"Configuration parameter type {value.type} does not match " ...
27,833
def split_dataset(dataset_file, trainpct): """ Split a file containing the full path to individual annotation files into train and test datasets, with a split defined by trainpct. Inputs: - dataset_file - a .txt or .csv file containing file paths pointing to annotation files. (Expects that t...
27,834
def accession(data): """ Get the accession for the given data. """ return data["mgi_marker_accession_id"]
27,835
def get_phase_dir(self): """Get the phase rotating direction of stator flux stored in LUT Parameters ---------- self : LUT a LUT object Returns ---------- phase_dir : int rotating direction of phases +/-1 """ if self.phase_dir not in [-1, 1]: # recalculate ...
27,836
def atomic_number(request): """ An atomic number. """ return request.param
27,837
def data_upgrades(): """Add any optional data upgrade migrations here!""" op.execute(''' UPDATE "ModuleForms" SET "Required" = 0 WHERE "Name" = 'Name' AND "Module_ID" = 2 ''')
27,838
def plot_metric(title = 'Plot of registration metric vs iterations'): """Plots the mutual information over registration iterations Parameters ---------- title : str Returns ------- fig : matplotlib figure """ global metric_values, multires_iterations fig, ax = plt....
27,839
def cross_entropy(model, _input, _target): """ Compute Cross Entropy between target and output diversity. Parameters ---------- model : Model Model for generating output for compare with target sample. _input : theano.tensor.matrix Input sample. _target : theano.tensor.matrix ...
27,840
def paste(): """Paste and redirect.""" text = request.form['text'] # TODO: make this better assert 0 <= len(text) <= ONE_MB, len(text) with UploadedFile.from_text(text) as uf: get_backend().store_object(uf) lang = request.form['language'] if lang != 'rendered-markdown': wi...
27,841
def get_groups_links(groups, tenant_id, rel='self', limit=None, marker=None): """ Get the links to groups along with 'next' link """ url = get_autoscale_links(tenant_id, format=None) return get_collection_links(groups, url, rel, limit, marker)
27,842
def over(expr: ir.ValueExpr, window: win.Window) -> ir.ValueExpr: """Construct a window expression. Parameters ---------- expr A value expression window Window specification Returns ------- ValueExpr A window function expression See Also -------- ib...
27,843
def node_value(node: Node) -> int: """ Computes the value of node """ if not node.children: return sum(node.entries) else: value = 0 for entry in node.entries: try: # Entries start at 1 so subtract all entries by 1 value += node_val...
27,844
def load_mac_vendors() : """ parses wireshark mac address db and returns dict of mac : vendor """ entries = {} f = open('mac_vendors.db', 'r') for lines in f.readlines() : entry = lines.split() # match on first column being first six bytes r = re.compile(r'^([0-9A-F]{2}:[0-9A-F]{...
27,845
def parse_time(s): """ Parse time spec with optional s/m/h/d/w suffix """ if s[-1].lower() in secs: return int(s[:-1]) * secs[s[-1].lower()] else: return int(s)
27,846
def resize_labels(labels, size): """Helper function to resize labels. Args: labels: A long tensor of shape `[batch_size, height, width]`. Returns: A long tensor of shape `[batch_size, new_height, new_width]`. """ n, h, w = labels.shape labels = F.interpolate(labels.view(n, 1, h, w).float(), ...
27,847
def export_search(host, s, password, export_mode="raw", out=sys.stdout, username="admin", port=8089): """ Exports events from a search using Splunk REST API to a local file. This is faster than performing a search/export from Splunk Python SDK. @param host: splunk server address @param s: search t...
27,848
def _extract_urls(html): """ Try to find all embedded links, whether external or internal """ # substitute real html symbols html = _replace_ampersands(html) urls = set() hrefrx = re.compile("""href\s*\=\s*['"](.*?)['"]""") for url in re.findall(hrefrx, html): urls.add(str(url)...
27,849
def reorganize_data(texts): """ Reorganize data to contain tuples of a all signs combined and all trans combined :param texts: sentences in format of tuples of (sign, tran) :return: data reorganized """ data = [] for sentence in texts: signs = [] trans = [] for sign,...
27,850
def stop(check_name, flavor, instance_name, remove, direct, location): """Stops an integration. \b $ di stop -r nginx Stopping containers... success! Removing containers... success! """ if check_name not in Checks: echo_failure('Check `{}` is not yet supported.'.format(check_name)) ...
27,851
def client_new(): """Create new client.""" form = ClientForm(request.form) if form.validate_on_submit(): c = Client(user_id=current_user.get_id()) c.gen_salt() form.populate_obj(c) db.session.add(c) db.session.commit() return redirect(url_for('.client_view', ...
27,852
def query_schema_existence(conn, schema_name): """Function to verify whether the current database schema ownership is correct.""" with conn.cursor() as cur: cur.execute('SELECT EXISTS(SELECT 1 FROM information_schema.schemata WHERE SCHEMA_NAME = %s)', [schema_name]) return cu...
27,853
def get_number_of_params(model, trainable_only=False): """ Get the number of parameters in a PyTorch Model :param model(torch.nn.Model): :param trainable_only(bool): If True, only count the trainable parameters :return(int): The number of parameters in the model """ return int(np.sum([np.pro...
27,854
def _test_conv_adj_fourier_hrf(ai_s, hrf): """ Helper to test the adj conv with a Fourier implementation, the kernel being the HRF. """ adj_ar_s_ref = simple_retro_convolve(hrf, ai_s) adj_ar_s_test = spectral_retro_convolve(hrf, ai_s) assert(np.allclose(adj_ar_s_ref, adj_ar_s_test, atol=1.0e-7))
27,855
def chart1(request): """ This view tests the server speed for transferring JSON and XML objects. :param request: The AJAX request :return: JsonResponse of the dataset. """ full_url = HttpRequest.build_absolute_uri(request) relative = HttpRequest.get_full_path(request) base_url = full_...
27,856
async def async_setup_platform( hass: HomeAssistant, _: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Add lights from the main Qwikswitch component.""" if discovery_info is None: return qsusb = hass.data[QWIKSWITCH] ...
27,857
def conv3x3(in_planes, out_planes, stride=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, bias=False)
27,858
def img_mime_type(img): """Returns image MIME type or ``None``. Parameters ---------- img: `PIL.Image` PIL Image object. Returns ------- mime_type : `str` MIME string like "image/jpg" or ``None``. """ if img.format: ext = "." + img.format return mime...
27,859
def test_subnet_mask_subnet_to_num(): """Test SubnetMask subnet to number converter""" assert SubnetMask._subnet_to_num(None) is None assert SubnetMask._subnet_to_num(24) == 24 assert SubnetMask._subnet_to_num('24') == 24 assert SubnetMask._subnet_to_num(None, subnet_type='ipv4') is None assert...
27,860
def set_log_level(verbose, match=None, return_old=False): """Convenience function for setting the logging level Parameters ---------- verbose : bool, str, int, or None The verbosity of messages to print. If a str, it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that thes...
27,861
def test_penalty_htlc_tx_timeout(node_factory, bitcoind, chainparams): """ Test that the penalizing node claims any published HTLC transactions Node topology: l1 <-> l2 <-> l3 <-> l4 ^---> l5 l1 pushes money to l5, who doesn't fulfill (freezing htlc across l2-l3) ...
27,862
def export_concept_samples(num_samples = 100, path_to_file = './samples.csv', labeling_threshold = 0.9): """Samples 'num_samples' points each concept, labels it with the concept with highest membership as well as all concepts with a membership above the labeling_threshold (relative to the highest membership con...
27,863
def print_formatted_text( output: Output, formatted_text: AnyFormattedText, style: BaseStyle, style_transformation: Optional[StyleTransformation] = None, color_depth: Optional[ColorDepth] = None, ) -> None: """ Print a list of (style_str, text) tuples in the given style to the output. ""...
27,864
def check_satisfy_dataset(w, D, involved_predicates=[]): """ This function is to check whether all facts in ``D'' have been installed in each of ruler intervals of the given Window ``w'' if facts in ruler intervals holds in ``D''. Args: w (a Window instance): D (dictionary of dictionary ...
27,865
def interp_at(d, g, varargs=None, dim=None, dask="parallelized"): """ Interpolates a variable to another. Example : varargs = [THETA, mld] : THETA(t, z, y, x) is interpolated with Z=mld(t, y, x) """ var, coordvar = varargs dim = ( dim if dim is not None else set(d[var].dims).difference(d...
27,866
def get_history(): """Get command usage history from History.sublime-project""" f = open('%s/%s/%s' % (sublime.packages_path(), "TextTransmute", "History.sublime-project"), 'r') content = f.readlines() f.close() return [x.strip() for x in conten...
27,867
def inprogress(metric: Gauge, labels: Dict[str, str] = None) -> Callable[..., Any]: """ This decorator provides a convenient way to track in-progress requests (or other things) in a callable. This decorator function wraps a function with code to track how many of the measured items are in progress....
27,868
def b58_wrapper_to_b64_public_address(b58_string: str) -> Optional[str]: """Convert a b58-encoded PrintableWrapper address into a b64-encoded PublicAddress protobuf""" wrapper = b58_wrapper_to_protobuf(b58_string) if wrapper: public_address = wrapper.public_address public_address_bytes = pub...
27,869
def test_pick_identifier_with_cover_task(app, testdata): """Test to update cover_metadata.""" doc = testdata["documents"][1] pick_identifier_with_cover(app, record=doc) tasks.save_record.assert_called_once() series = testdata["series"][1] pick_identifier_with_cover(app, record=series) asser...
27,870
def render_to_AJAX(status, messages): """return an HTTP response for an AJAX request""" xmlc = Context({'status': status, 'messages': messages}) xmlt = loader.get_template("AJAXresponse.xml") response = xmlt.render(xmlc) return HttpResponse(response)
27,871
def laplace(loc=0.0, scale=1.0, size=None): # real signature unknown; restored from __doc__ """ laplace(loc=0.0, scale=1.0, size=None) Draw samples from the Laplace or double exponential distribution with specified location (or mean) and scale (decay). The Laplace d...
27,872
def parse_params(environ, *include): """Parse out the filter, sort, etc., parameters from a request""" if environ.get('QUERY_STRING'): params = parse_qs(environ['QUERY_STRING']) else: params = {} param_handlers = ( ('embedded', params_serializer.unserialize_string, None), ('filter', params_serializer.unseri...
27,873
def _attribute_is_an_ipv4( attribute_name, attribute_value, bridge_name, port_name ): """ Check if an attribute is an IPv4 address :param attribute_name: The attribute name :param attribute_value: The attribute value :param bridge_name: The attribute bridge name :param port_name: The attribu...
27,874
def create_dict_facade_for_object_vars_and_mapping_with_filters(cls, # type: Type[Mapping] include, # type: Union[str, Tuple[str]] exclude, ...
27,875
def now(): """ 此时的时间戳 :return: """ return int(time.time())
27,876
def get_yourContactINFO(rows2): """ Function that returns your personal contact info details """ yourcontactINFO = rows2[0] return yourcontactINFO
27,877
def hafnian( A, loop=False, recursive=True, rtol=1e-05, atol=1e-08, quad=True, approx=False, num_samples=1000 ): # pylint: disable=too-many-arguments """Returns the hafnian of a matrix. For more direct control, you may wish to call :func:`haf_real`, :func:`haf_complex`, or :func:`haf_int` directly. ...
27,878
def test_aws_lambda_handler_default_environment(mock_ec2paramstore, mock_create_app, mock_awsgi_response): """ Tests that the aws lambda handler correctly processes environ variables and sets up the app correctly without environmental variables set """ default_environ = { "config_name": "ebr_boa...
27,879
def filter_out_nones(data): """ Filter out any falsey values from data. """ return (l for l in data if l)
27,880
def start(args_string): """Launch and display a TensorBoard instance as if at the command line. Args: args_string: Command-line arguments to TensorBoard, to be interpreted by `shlex.split`: e.g., "--logdir ./logs --port 0". Shell metacharacters are not supported: e.g., "--logdir 2>&1" wil...
27,881
def BytesToGb(size): """Converts a disk size in bytes to GB.""" if not size: return None if size % constants.BYTES_IN_ONE_GB != 0: raise calliope_exceptions.ToolException( 'Disk size must be a multiple of 1 GB. Did you mean [{0}GB]?' .format(size // constants.BYTES_IN_ONE_GB + 1)) retu...
27,882
def build_report(drivers: dict, desc=False) -> [[str, str, str], ...]: """ Creates a race report: [[Driver.name, Driver.team, Driver.time], ...] Default order of drivers from best time to worst. """ sorted_drivers = sort_drivers_dict(drivers, desc) return [driver.get_stats for driver in sorted_d...
27,883
def add_sites_sheet(ws, cols, lnth): """ """ for col in cols: cell = "{}1".format(col) ws[cell] = "='Capacity_km2_MNO'!{}".format(cell) for col in cols[:2]: for i in range(2, lnth): cell = "{}{}".format(col, i) ws[cell] = "='Capacity_km2_MNO'!{}"...
27,884
def testBinaryFile(filePath): """ Test if a file is in binary format :param fileWithPath(str): File Path :return: """ file = open(filePath, "rb") #Read only a couple of lines in the file binaryText = None for line in itertools.islice(file, 20): if b"\x00...
27,885
def collect(mail_domain): """ Attempt to connect to each MX hostname for mail_doman and negotiate STARTTLS. Store the output in a directory with the same name as mail_domain to make subsequent analysis faster. """ print "Checking domain %s" % mail_domain mkdirp(os.path.join(CERTS_OBSERVED, mail_domain)) ...
27,886
def launch_experiment( script, run_slot, affinity_code, log_dir, variant, run_ID, args, python_executable=None, set_egl_device=False, ): """Launches one learning run using ``subprocess.Popen()`` to call the python script. Calls the scr...
27,887
def dup_max_norm(f, K): """ Returns maximum norm of a polynomial in ``K[x]``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x = ring("x", ZZ) >>> R.dup_max_norm(-x**2 + 2*x - 3) 3 """ if not f: return K.zero else: return max(dup_abs(f, K))
27,888
def greedy_algorithm(pieces, material_size): """Implementation of the First-Fit Greedy Algorithm Inputs: pieces - list[] of items to place optimally material_size - length of Boards to cut from, assumes unlimited supply Output: Optimally laid out BoardCollection.contents, which is a list[] of ...
27,889
def start_tv_session(hypes): """ Run one evaluation against the full epoch of data. Parameters ---------- hypes : dict Hyperparameters Returns ------- tuple (sess, saver, summary_op, summary_writer, threads) """ # Build the summary operation based on the TF coll...
27,890
def factor_size(value, factor): """ Factors the given thumbnail size. Understands both absolute dimensions and percentages. """ if type(value) is int: size = value * factor return str(size) if size else '' if value[-1] == '%': value = int(value[:-1]) return '{0}%...
27,891
def categoryProfile(request, pk): """ Displays the profile of a :class:`gestion.models.Category`. pk The primary key of the :class:`gestion.models.Category` to display profile. """ category = get_object_or_404(Category, pk=pk) return render(request, "gestion/category_profile.html", {"ca...
27,892
def test_tokens_mysql(): """ testing for mysql specific parsing """ for testname in sorted(glob.glob('../tests/test-tokens_mysql-*.txt')): testname = os.path.basename(testname) yield run_tokens_mysql, testname
27,893
def eoms(_x, t, _params): """Rigidy body equations of motion. _x is an array/list in the following order: q1: Yaw q2: Lean |-(Euler 3-1-2 angles used to orient A q3: Pitch / q4: N[1] displacement of mass center. q5: N[2] displacement of mass center. q6: ...
27,894
def memoize_with_hashable_args(func): """Decorator for fast caching of functions which have hashable args. Note that it will convert np.NaN to None for caching to avoid this common case causing a cache miss. """ _cached_results_ = {} hash_override = getattr(func, "__hash_override__", None) i...
27,895
def _download_from_s3(fname, bucket, key, overwrite=False, anon=True): """Download object from S3 to local file Parameters ---------- fname : str File path to which to download the object bucket : str S3 bucket name key : str S3 key for the object to download over...
27,896
def restore_cursor() -> None: """Restore cursor position as saved by `save_cursor`.""" terminal.write("\x1b[u")
27,897
def _fill_feature_values(data_values, feature_names, languages): """Adds feature values to languages dictionary.""" logging.info("Filling feature values for languages ...") for value_id in range(len(data_values)): values = data_values[value_id] feature_name = values[_PARAM_ID] cur_value_code = feature...
27,898
def create_nem_xml( emane_model: "EmaneModel", config: Dict[str, str], nem_file: str, transport_definition: str, mac_definition: str, phy_definition: str, server: DistributedServer, ) -> None: """ Create the nem xml document. :param emane_model: emane model to create xml :pa...
27,899