content
stringlengths
22
815k
id
int64
0
4.91M
def callback_weather(data): """ Callback for receiving data from /weather ROS topic :param data: Data from /weather ROS topic """ global weather_status weather_status = data
5,310,200
def _get( parser: Union[Optional[ConfigParser], SectionProxy], key: str, overrides: Optional[Dict[str, Any]], defaults: Dict[str, Any] ) -> Any: """Get a value from a parser, overriding or setting a default as necessary.""" override = overrides[key] if overrides and key in overrides else None default = ...
5,310,201
def add_ovs_flows(): """Add Openflow rules to redirect traffic between client and server to vnf.""" check_output(split("ovs-ofctl del-flows s1")) check_output( split( 'ovs-ofctl add-flow s1 "{proto},in_port={in_port},actions=output={out_port}"'.format( **{ ...
5,310,202
def get_rate(net_card): """ 统计每秒接收到的数据大小 :parma net_card: 网卡名字 :return : 返回未格式化的信息 """ net_cards = [] old = [0, 0, 0, 0] new = [0, 0, 0, 0] if net_card is None: # 抓取全部网卡的速度 net_cards = net_io_counters(pernic=True).keys() else: net_cards.append(net_card) for c...
5,310,203
def get_application(rawEvent): """Return application details.""" application = dict() application["external_ip"] = rawEvent["details"]["browser"]["address"] # Process user agent string. userAgent = rawEvent["details"]["browser"]["user-agent"] application["name"] = httpagentparser.detect(userAg...
5,310,204
def generate_pileup_file(sample_name, outpath, gzip_pileup, alignment_file, alignment_summary, probe_file, mtdna_refseq, qual_min, mtdna_offset): """ a function wrapper to generate the pileup file from the alignment file using samtools mtdna positions are corrected to those of rCRS Arguments ---------- sample_n...
5,310,205
def steering(taus, n_fft): """ This function computes a steering vector by using the time differences of arrival for each channel (in samples) and the number of bins (n_fft). The result has the following format: (batch, time_step, n_fft/2 + 1, 2, n_mics). Arguments: ---------- taus : tensor ...
5,310,206
def shoot(lon, lat, azimuth, maxdist=None): """Shooter Function Original javascript on http://williams.best.vwh.net/gccalc.htm Translated to python by Thomas Lecocq """ import numpy as np glat1 = lat * np.pi / 180. glon1 = lon * np.pi / 180. s = maxdist / 1.852 faz = azimuth * np.pi ...
5,310,207
def subsitute(clause: Clause, transformation: Dict[Argument, Argument]) -> Clause: """Applies given transformations to the clause. Example: X -> a for P(X) will result in P(a) """ for t in transformation: clause = Clause( frozenset([substitute_literal(l, t, transformation[t]) ...
5,310,208
def test_hapd_ctrl_chan_switch(dev, apdev): """hostapd and CHAN_SWITCH ctrl_iface command""" ssid = "hapd-ctrl" params = { "ssid": ssid } hapd = hostapd.add_ap(apdev[0], params) if "FAIL" not in hapd.request("CHAN_SWITCH "): raise Exception("Unexpected CHAN_SWITCH success") if "FAIL" not...
5,310,209
def get_loss_fn_v2(loss_factor=1.0): """Gets a loss function for squadv2.0 task""" def _loss_fn(labels, model_outputs): start_positions = labels['start_positions'] end_positions = labels['end_positions'] is_impossible = labels['is_impossible'] _, start_logits, end_logits, cls_log...
5,310,210
def BuildUniverse( use_simplified_universe: bool = False, modified_types_filepath: str = None, ) -> presubmit_validate_types_lib.ConfigUniverse: """Generates the ontology universe. Args: use_simplified_universe: boolean to quick load minimal universe instead of full ontology modified_types_fi...
5,310,211
def decodeXMLName(name): """ Decodes an XML (namespace, localname) pair from an ASCII string as encoded by encodeXMLName(). """ if name[0] is not "{": return (None, name.decode("utf-8")) index = name.find("}") if (index is -1 or not len(name) > index): raise ValueError("Invalid enc...
5,310,212
def get_windowing(data): """ Retrieves windowing data from dicom metadata Arguments: data {pydicom data obj} -- object returned from pydicom dcmread() Attribution: This code comes from Richard McKinley's Kaggle kernel """ dicom_fields = [data.WindowCenter, data.Windo...
5,310,213
def update_fits(image_name, data=None, header=None): """Safely replaces a fits image with new data and/or header Uses the astropy.io.fits pacakge. astropy.io.fits.writeto contains a clobber parameter which should allow replacement of one fits file by another of the same ...
5,310,214
def test_update_deployment() -> None: """Test for updation of a deployment""" make_fake_deployment() request_json: Dict[str, Any] = { "compose_file": "fake compose file content", "env_file": "BAZ=baz", "databases": { "db2": { "username": "root" ...
5,310,215
def convert_mat_non_zero_to_inv_mat(n: int, non_zero_idx_pairs: List[Tuple[int,int]], mat_non_zero: np.array) -> np.array: """Convert list of matrice's non-zero elements into the matrice's inverse Args: n (int): Size of matrix non_zero_idx_pairs (List[Tuple[int,int]]): List of non-zero index p...
5,310,216
def run(**settings): """Start the application. Parameters: host: Interface to listen on. [default: 0.0.0.0] port: TCP port to listen on. [default: 8888] log: The log file to use, the default is sys.stdout. base_handler: The class or factory for request handlers. The default ...
5,310,217
def Logger_stringToLevel(str): """ Logger.stringToLevel(s) parses a string and returns a Logger::Level :param str s: the string to parse. """ return _roadrunner.Logger_stringToLevel(str)
5,310,218
def execute(command, data_in=None, timeout=0, error=None): """ Execute a command and capture outputs. On Python 2.6 it adds an option to ignore the deprecation warning from the cryptography package after the first entry of the command parameter. @param command: executable to run and arguments to u...
5,310,219
def temporarily_change_directory(file_path): """A context to temporarily change the working directory. Parameters ---------- file_path: str The file path to temporarily change into. """ prev_dir = os.getcwd() os.chdir(os.path.abspath(file_path)) try: yield finally: ...
5,310,220
def run(command_line, manager_run, capture_stderr=False): """ Returns tuple of standard output and exit code """ sys_stderr_orig = sys.stderr if capture_stderr: sys.stderr = StringIO.StringIO() sys.argv = command_line.split() try: manager_run() except SystemExit: ...
5,310,221
def get_time_index(path,f): """Calculate the number and mass of objects around the centre of mass fro a fixed bubble size. Parameters ---------- path Location of hdf5 file from NBODY. f hdf5 file Returns ------- hdf_index The index in hdf5 file corresponding t...
5,310,222
def process(buf: Buffer): """ Collects data from ARP messages. Target address are collected just for replies. """ eth_frame = ethernet.Ethernet.read_from_buffer(buf) if eth_frame.next_header == ethernet.ETHER_TYPE_ARP: arp_frame = arp.ARP.read_from_buffer(buf) if arp_frame.operation == arp.OPERATION_REPLY: ...
5,310,223
def save_perm_score(perm_scores, fn, output_folder): """ Save the permutation scores to a NumPy array file. """ fn = fn + '.npy' output_path = join(output_folder, fn) np.save(output_path, perm_scores) return output_path
5,310,224
def htmlencode(text): """Use HTML entities to encode special characters in the given text.""" text = text.replace('&', '&amp;') text = text.replace('"', '&quot;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') return text
5,310,225
def append_entries( log: list[Entry], *, previous_index: int, previous_term: int, entries: list[Entry], ) -> bool: """Append entries to the log. This is both idempotent and destructive. If an entry is identical to the entry that already exists at the index, it, along with any subseq...
5,310,226
def request(file_path): """Request file by the file path.""" try: data = read_file(file_path) mime_type = get_mime_type(file_path) return data, mime_type, STATUS_CODES['success'] except Exception: return server_error()
5,310,227
def v_include_complex_type(ctx, stmt): """Loads complex-types from a submodule. Checks for complex-type collisions in a submodule. """ includes = stmt.search('include') def get_module(i): # check if the module to import is already added modulename = i.arg r = i.sear...
5,310,228
def test_method_call_to_style_conversion(method_name, expected): """ Test converting the method call to an actual style """ colorful = core.Colorful(colormode=terminal.ANSI_8_COLORS) method = getattr(colorful, method_name) assert str(method('No, I am your father')) == expected
5,310,229
def fix_roots(poles, fix_roots="incr", fix_mode="reflect"): """ Fix (stabilize) LP roots. Parameters ---------- poles : ndarray Array of LP roots (poles). fix_roots : {'incr', 'decr'} Type of roots which to consider bad and to stabilize. Either those with increasing sig...
5,310,230
def parse_keyword_args(keywords: Iterable[str], args: str) -> (Dict[str, str], str): """ :param keywords: Valid keywords :param args: String argument to parse :return: (Dict of kwargs, remaining part of args) """ kwargs = {} matches = _KWARG_RE.match(args) while matches is not None: ...
5,310,231
def is_lambda(fun): """ Check whether the given function is a lambda function. >>> def not_lambda_fun(): ... return None ... >>> lambda_fun = lambda: None ... >>> print( ... is_lambda(not_lambda_fun), ... is_lambda(lambda_fun) ...
5,310,232
def _read_gaussian_container(g_file): """Read a gaussian container in a binary format""" # gaussian container chk = g_file.read(8) # read string of 8bytes if chk != "GAUSSVEC": raise Exception("Error: the gaussian container" + " is not of GAUSSVEC kind %s" % chk) gc...
5,310,233
def _save_dict_npz(dct, path, compression=False): """Save a dictionary of numpy arrays into a (npz) file. Parameters ---------- dct : dictionary The dictionary to save. path : string The path of the file. compression : boolean (``False``) If ``True`` the data will be sav...
5,310,234
def voigt_kernel(k, beta,gammaL): """Fourier Kernel of the Voigt Profile Args: k: conjugated of wavenumber beta: Gaussian standard deviation gammaL: Lorentian Half Width Returns: kernel (N_x,N_beta,N_gammaL) Note: Conversions to the (full) width...
5,310,235
def test_fileformatjson_pass_with_substitutions(fs): """Relative path to file should succeed.""" payload = """{ "key1": "{k1}value !£$% *", "key2_{k2}": { "k21": "value", "abc": "{k3} def {k4}", "def": [ "l1", "l2 {k5}", "l3" ] } } """ in_path = './tests/testfiles/tes...
5,310,236
def prepare_questions(questions_json): """ Tokenize and normalize questions from a given question json in the usual VQA format. """ questions = [q['question'] for q in questions_json['questions']] for question in questions: question = question.lower()[:-1] yield question.split(' ')
5,310,237
def test_session_is_captured(client, log_capture, settings): """ test if session_id is captured in logs and if persists through the calls""" resp = client.get("/logging_with_session") assert resp.status_code == 200 session_id = resp.json()["session_id"] # call it again client.get("/logging_wit...
5,310,238
def BOPTools_AlgoTools_GetEdgeOff(*args): """ * Returns True if the face theFace contains the edge theEdge but with opposite orientation. If the method returns True theEdgeOff is the edge founded :param theEdge: :type theEdge: TopoDS_Edge & :param theFace: :type theFace: TopoDS_Face & :param ...
5,310,239
def parse_args() -> argparse.Namespace: """Parse user command line arguments.""" parser = argparse.ArgumentParser( prog="ssacc", description="Map SSA County Codes to ZIP Codes.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "-r", ...
5,310,240
def get_voc( df, fit_window = 20 ): """ Get open circuit voltage. :param df: A Pandas DataFrame containing JV sweeps, indexed by voltage. :param fit_window: Window size to extrapolate if needed. [Default: 20] :returns: A Pandas Series of open circuit voltages. """ df = df.sort_index() ...
5,310,241
def Merge(A, p, q, r): """Combina dos subsecuencias ordenadas dentro de un arreglo.""" n1 = q - p + 1 n2 = r - q L = [] R = [] for i in range(n1): L.append(A[p + i]) for j in range(n2): R.append(A[q + j + 1]) L.append(9999999) R.append(9999999) i = 0 j = 0 ...
5,310,242
async def test_qos_encoding_custom(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test custom qos and encoding.""" mqtt_mock = await mqtt_mock_entry_no_yaml_config() @callback def msg_callback(*args): """Do nothing.""" pass sub_state = None sub_state = async_prepare_subscrib...
5,310,243
def calc_Rrup( Rx, Ztor, W, dip, azimuth, Rjb=None ): """ Compute the closest distance from site the the surface the fault """ if Ztor < 0: print 'Ztor should be larger than 0' raise ValueError if W <= 0: print 'Fault width should be larger than 0' raise ValueError if dip<=0 or dip > 90: pr...
5,310,244
def getImagesAndLabels(path: str, resizeDims: int): """ For all images in a directory, returns resized images in an array with a corresponding label based on their subdirectory. """ images = [] labels = [] for dir_path in glob.glob(path): img_label = dir_path.split("\\")[-1]...
5,310,245
def split_video_into_chunks(item): """ :param item :return: """ item['subtitles'] = clean_subtitles(item['subtitles']) vtt = pd.DataFrame(item['subtitles']) if 'word' not in vtt.columns: raise ValueError(f"'Word' not in item['subtitles'] \n{item}") if 'title' not in item['info']:...
5,310,246
def test(): """ Testing Docstring""" pass if __name__=='__main__': test()
5,310,247
def not_equal(a, b): #pdb.set_trace() """ return 1 if True, else 0 """ name = "not_equal" a2, b2 = COPY(a), COPY(b) c = saferound(a2, sigfigs) != saferound(b2, sigfigs) get_hashes(c, a, b) return(bound(c))
5,310,248
def confidence_interval(A, axis=None, alpha=.05, metric=np.mean, numResamples=1000, interpolate=True): """ Bootstrap confidence interval. Return the bootstrap confidence interval of an array or along an axis ignoring NaNs and masked elements. Parameters ---------- A...
5,310,249
def read_audio_record(audio_record, output_to_file=None): """ #https://stackoverflow.com/questions/42703849/audioset-and-tensorflow-understanding """ vid_ids = [] labels = [] start_time_seconds = [] # in secondes end_time_seconds = [] feat_audio = [] count = 0 with tf.device("/c...
5,310,250
async def command(client, param, ctx): """ Syntax: ~info Description: Shares information about Swashbot """ tmp = "https://api.github.com/repos/almonds0166/swashbot/git/refs/heads/master" async with aiohttp.ClientSession() as session: async with session.get(tmp) as resp: ...
5,310,251
def _remove_source_ip_ubt_v1(vrf_name, **kwargs): """ Perform GET and PUT calls to remove the source IP address for UBT on a VRF. :param vrf_name: Alphanumeric name of VRF :param kwargs: keyword s: requests.session object with loaded cookie jar keyword url: URL in main() function :r...
5,310,252
def create_trigger_instance(trigger, payload, occurrence_time): """ This creates a trigger instance object given trigger and payload. Trigger can be just a string reference (pack.name) or a ``dict`` containing 'type' and 'parameters'. :param trigger: Dictionary with trigger query filters. :typ...
5,310,253
def app_configuration(): """ Gets the settings for the app for use in other functions and ajax for leaflet Dependencies: os, App (app) """ return { 'app_wksp_path': os.path.join(App.get_app_workspace().path, ''), 'threddsurl': App.get_custom_setting("Thredds WMS URL"), 'geose...
5,310,254
def move_to_location( object_instance: Dict[str, Any], location: Dict[str, Any], object_bounds: List[Dict[str, float]], previous_object: Dict[str, Any] ) -> Dict[str, Any]: """Move the given object to a new location and return the object.""" new_location = copy.deepcopy(location) if previous...
5,310,255
def findStationsWithinBoundingBox(config, bbox): """ Find stations that lie within a bounding box @param config ConfigParser containing the section 'GHCND' and option 'PATH_OF_STATION_DB' @param bbox A dict containing keys: minX, minY, maxX, maxY, srs, where srs='EPSG:4326' ...
5,310,256
def display_by_method(data, fp): """Print the profiler data with each sample function represented as one row in a table. Important lines within that function are output as nested rows. Sorted by self-time per line.""" fp.write( b'%5.5s %10.10s %7.7s %-8.8s\n' % (b'% ', b'cumulative...
5,310,257
def start_engine() -> Any: """ """ global MATLAB_ENGINE if not MATLAB_ENGINE: from matlab import engine print("Starting Matlab") if True: MATLAB_ENGINE = engine.start_matlab() else: future = engine.start_matlab(background=True) MATLAB_ENGI...
5,310,258
def main(lang): """The hypermodern Python project.""" data = wikipedia.random_page() title = data["title"] extract = data["extract"] click.secho(title, fg="green") click.echo(textwrap.fill(extract))
5,310,259
def format_seq(seq,stop=False): """ Takes an amino acid sequence, returns a list of integers in the codex of the babbler. Here, the default is to strip the stop symbol (stop=False) which would have otherwise been added to the end of the sequence. If you are trying to generate a rep, do not include t...
5,310,260
def commit(using=None): """Commit a transaction.""" get_connection(using).commit()
5,310,261
def select_without_privilege(self, node=None): """Check that user is unable to select from a distributed table without privileges. """ user_name = f"user_{getuid()}" table0_name = f"table0_{getuid()}" table1_name = f"table1_{getuid()}" exitcode, message = errors.not_enough_privileges(name=f"{us...
5,310,262
def parser_maximum_bitrate_Descriptor(data,i,length,end): """\ parser_maximum_bitrate_Descriptor(data,i,length,end) -> dict(parsed descriptor elements). This descriptor is not parsed at the moment. The dict returned is: { "type": "maximum_bitrate", "contents" : unparsed_descriptor_contents } ...
5,310,263
def test_set_order_sparse(order, input_order): """Check that _set_order returns sparse matrices in promised format.""" X = sparse.coo_matrix(np.array([[0], [0], [0]])) y = sparse.coo_matrix(np.array([0, 0, 0])) sparse_format = "csc" if input_order == "F" else "csr" X = X.asformat(sparse_format) ...
5,310,264
def VACFtraj(traj, dt=1): """ Calculate/give velocity autocorrelation for a single trajectory. The result of the calculation is stored in ``traj.meta['VACF']`` and ``traj.meta['VACFmeta']``. This function checks whether the corresponding fields exist and if not calculates them. It then returns the ...
5,310,265
def status(request): """ Returns a simple HttpResponse """ response = "<h1>%s</h1>" % getattr(settings, 'PING_DEFAULT_RESPONSE', PING_DEFAULT_RESPONSE) content_type = getattr(settings, 'PING_DEFAULT_CONTENT_TYPE', PING_DEFAULT_CONTENT_TYPE) if request.GET.get('checks') == 'true': respo...
5,310,266
def load_artificio_potencial(): """\nload_artificio_potencial():\n Funcion utilizada para llenar el archivo csv: artificio_potencial.csv. Se debe llenar de la siguiente manera: * sum. 1er termino: Suma de primer termino debe ser un numero entero, cero(0) o uno(1) ...
5,310,267
def get_healthcare_py_str(): """ Get the code str for the adult_easy pipeline """ with open(HEALTHCARE_PY) as file: test_code = file.read() return test_code
5,310,268
def create_cluster_metadata(topic_partitions): """Create ClusterMetada out of a dict structure for easier mocking. topic_partitions should be in the format of {'topic1': [partition1, partition2], 'topic2': [partition3]...} """ cluster_metadata = ClusterMetadata() topics_dict = {} for topic in t...
5,310,269
async def custom_request_validation_exception_handler( request: Request, exception: RequestValidationError ) -> JSONResponse: """Custom handling of fastapi request validation errors""" log.error(f'{request.method} {request.url.path} : {str(exception)}') if route_has_tag(request, constants.V1_TAG): ...
5,310,270
def run_tasklet(tasklet_ast: ast.With, filename: str, gvars: Dict[str, Any], lvars: Dict[str, Any]): """ Transforms and runs a tasklet given by its AST, filename, global, and local variables. :param tasklet_ast: AST of the "with dace.tasklet" statement. :param filename: A string representing the ori...
5,310,271
def complete_line(base_coord, targ_coord, word_len, row_length, column_length): """Return list of tuple coordinates which correspond to a straight line inside the matrix. Args: base_coord (tuple): A coordinate tuple of the starting position. targ_coord (tuple): A coordinate tuple of the target ...
5,310,272
def decompose(data_with_size: bytes) -> list: """ Deserialize a byte string into a list of byte strings. """ (buf, size) = extract_size(data_with_size) if size < 0: raise BadFile() xs = [] for i in range(size): (buf2, chunk_size) = extract_size(buf) chunk = buf2[:chu...
5,310,273
def _compute_name(name, extension, overwrite=False, path_name=SAVE_PATH): """Compute a file name, with the script name in prefix and time in suffix Parameters ---------- name: string The original name (e.g. "my_figure") extension: string The file extansion (e.g. ".txt") overwrit...
5,310,274
def find_stars (ra_cat, dec_cat, ra, dec, dist, search='box', sort=False): """find entries in [ra_cat] and [dec_cat] within [dist] of [ra] and [dec]; all in degrees """ # make a big cut in arrays ra_cat and dec_cat to speed up index_cut = np.nonzero(np.abs(dec_cat-dec)<=dist...
5,310,275
def pgatour_statistic(url): """Get data on give pgatour statistic Args: url (str) : pgatour statistic url Returns: data of pgatour statistic """ with requests.Session() as session: page = session.get(url) soup = BeautifulSoup(page.content, "lxml")...
5,310,276
def align_ners(amr, nodeid2token, unaligned_node_ids=None, flat_alignments=False, aformat=None): """ Align all elements on a NER subgraph that are not surface to the last of the surface symbols aformat = 'stack' ensures NER alignments match those of stack-lstm/Transformer oracle ...
5,310,277
def open_uniform_bspline(control_points: Iterable['Vertex'], order: int = 4, weights: Iterable[float] = None) -> BSpline: """ Creates an open uniform (periodic) `B-spline`_ curve (`open curve`_). This is an unclamped curve, which means the curve passes none of the control points. ...
5,310,278
def test_list_positive_integer_enumeration_3_nistxml_sv_iv_list_positive_integer_enumeration_4_5(mode, save_output, output_format): """ Type list/positiveInteger is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/positiveInteger/Schema+Instance/NISTSchema-SV-IV-list-p...
5,310,279
def test(): """运行这个单元测试""" import unittest default_config_name='TestConfig' tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
5,310,280
def parse_args(): """ Parse command line options into variables """ parser = optparse.OptionParser(usage="Usage: %prog [options]") parser.add_option("--film-urls", type="string", dest="urls", help=("Film URLs to pick from, separated by commas") ) parser.ad...
5,310,281
def get_services(path_obj): """ Return a list of GATT Service UUIDs for a given Bluetooth device D-Bus path :param path_obj: D-Bus path for remote Bluetooth device :return: List of GATT Service UUIDs """ found_services = [] valid_structure = re.match(r'/org/bluez/hci\d+/dev(_([0-9A-Fa-f]){2...
5,310,282
def get_env_generating_function(environment_config: EnvironmentConfig) -> t.Callable: """Returns a function that generates a Doom environment wrapper.""" return lambda: create_env(environment_config)
5,310,283
def normalize_error(error: str, error_types: set[str]) -> str: """Translate any "bad" error types to something more usable.""" error = app.config["OAUTH_FETCH_ERROR_TYPES"].get(error, error) if error not in error_types: return errors.SERVER_ERROR else: return error
5,310,284
def remove_duplicates(pot_path, metadata): """ FIXME: """ old_pot_name = pot_path + ".bak" os.rename(pot_path, old_pot_name) pot = polib.pofile(old_pot_name, wrapwidth=100000, check_for_duplicates=False) entries = {} entries_data = {} duplicates = set() for entry in pot: ...
5,310,285
def dict_to_joined_export(data, index, indices, name): """ Converts a dict into one or more tabular datasets """ output = {} # TODO: test for _geolocation and attachment lists if isinstance(data, dict): for key, val in data.iteritems(): if isinstance(val, list) and key not in...
5,310,286
def inf_get_af2(*args): """ inf_get_af2() -> uint32 """ return _ida_ida.inf_get_af2(*args)
5,310,287
def plural(items_or_count, singular: str, count_format='', these: bool = False, number: bool = True, are: bool = False) -> str: """Returns the singular or plural form of a word based on a count.""" try: count = len(items_or_count) except TypeEr...
5,310,288
def Jaccrad(str1, str2): """ S2a,S2b计算 :param str1: :param str2: :return: """ if (len(str1.split('=')) == 1)|(len(str2.split('=')) == 1): return 0, 0 # elif (str1 == 'None=str;1') | (str2 == 'None=str;1'): # return 0, 0 elif (len(str1.split(';')) == 1)|(len(str2.split...
5,310,289
def load_distance_matrix(layer): """ Returns the distance matrix as defined by the features of the provided layer Note that this must be generated beforehand using generate_dist_func :type layer: str :param layer: Feature layer :return: numpy array """ return hkl.load(os.path.join(dist...
5,310,290
def many_pairs_featurize( signature_pairs: List[Tuple[str, str, Union[int, float]]], dataset: ANDData, featurizer_info: FeaturizationInfo, n_jobs: int, use_cache: bool, chunk_size: int, nameless_featurizer_info: Optional[FeaturizationInfo] = None, nan_value: float = np.nan, delete_tr...
5,310,291
def db_setup(db_name): """Database setup.""" cxn = sqlite3.connect(db_name, timeout=30.0) cxn.execute('PRAGMA page_size = {}'.format(2 ** 16)) cxn.execute("PRAGMA journal_mode = WAL") return cxn
5,310,292
def _dstack_product(x, y): """Returns the cartesian product of the elements of x and y vectors. Args: x: 1d array y: 1d array of the same dtype as x. Returns: a 2D array containing the elements of [x]x[y]. Example: x = jnp.array([1, 2, 3]) y = jnp.array([4, 5] _dstack_product(x,y) ...
5,310,293
def remove_directory(folder: Path): """Remove a specific directory recursively Parameters ----------- folder : Path folder to be removed """ for p in folder.iterdir(): if p.is_dir(): remove_directory(p) else: p.unlink() folder.rmdir()
5,310,294
def restore_and_save_temporaries(kernel): """ Add code that loads / spills the temporaries in the kernel which are live across sub-kernel calls. """ # Compute live temporaries. live_in, live_out = compute_live_temporaries(kernel, kernel.schedule) # Create kernel variables based on live temp...
5,310,295
def load_piece(fn_xml, fn_match, return_all_parts = False, return_units = False): """ Load a musicxml file and a match file """ parts = parse_music_xml(fn_xml) assert len(parts) > 0 try: divs = float(parts[0].timeline.points[0].get_next_of_type(Divisions, True)[0].divs) except: ...
5,310,296
def readMIG(): """Reads the Mitutoyo profilometry gauges from HOST:PORT, returning the values as a list of strings. Bad gauge(es) are indicated by the string "MIG Error" instead of a value. """ # Open the network connection try: tn = Telnet(HOST, PORT) except: print('Telne...
5,310,297
def role_object_factory(role_name='role.test_role'): """Cook up a fake role.""" role = { 'nameI18n': role_name[:32], 'active': 1 } return role
5,310,298
def _impl_ufunc_acosh(a): """ Calculates an implementation-dependent approximation to the inverse hyperbolic cosine, having domain [+1, +infinity] and codomain [+0, +infinity], for each element x_i of the input array x. """ pass
5,310,299