content
stringlengths
22
815k
id
int64
0
4.91M
def bertScore(string): """ Function to generate the output list consisting top K replacements for each word in the sentence using BERT. """ corrector = SpellCorrector() temp1 = [] temp2 = [] temp3 = [] con = list(string.split(" ")) tf.reset_default_graph() sess = tf.InteractiveS...
39,700
def main(model_config, data_config, time, data_file_ext, ent_file_ext, rel_file_ext): """Main function for performing relation extraction training Args: model_config (dict): configuration for RE model data_config (dict): configuration of input data time (str): time marker for saving ...
39,701
def configuration_stub(configuration_test: Configuration) -> Configuration: """ Configuration for tests. """ return dataclasses.replace( configuration_test, distance_between_wheels=DISTANCE_BETWEEN_WHEELS, )
39,702
def join_smiles(df, df_smiles=None, how="left"): """Join Smiles from Compound_Id.""" if df_smiles is None: load_resource("SMILES") df_smiles = SMILES result = df.merge(df_smiles, on="Compound_Id", how=how) result = result.apply(pd.to_numeric, errors='ignore') result = result.fillna("...
39,703
def send(to=None, cc=None, bcc=None, from_address="no-reply", from_name=None, subject=None, text=None, html=None, attachments=None, inline_attachments=None): """Send an email""" pass
39,704
def signature(*types, **kwtypes): """Type annotations and conversions for methods. Ignores first parameter. """ conversions = [(t if isinstance(t, tuple) else (t, t)) for t in types] kwconversions = {k: (t if isinstance(t, tuple) else (t, t)) for k, t in kwtypes.items()} d...
39,705
def mean(image): """The mean pixel value""" return image.mean()
39,706
def test_referenceurlsmodel_validate_genome_version(): """test ReferenceUrlsModel for validating genome version """ # GIVEN a reference model dummy_output_file = "some_random_file" dummy_output_path = "some_path" actual_path = Path(dummy_output_path, dummy_output_file).as_posix() dummy_referenc...
39,707
def read_event_file(file_name): """Read a file and return the corresponding objects. :param file_name: Name of file to read. :type file_name: str :returns: ServiceEvent from file. :rtype: ServiceEvent """ with open(file_name, 'r') as f: contents = yaml.safe_load(f) event = Servi...
39,708
def hibernate(): # This Popen reference failed """subprocess.Popen("C:\\Windows\\System32\\cmd.exe", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate(input=b"shutdown /h")""" system("shutdown /h")
39,709
def create_basic_cnn_model(num_classes: int): """ Function to create a basic CNN. :param num_classes: The number of classes (labels). :return: A basic CNN model. """ model = Sequential() # Convolutional + spooling layers model.add(Conv2D(64, (5, 5), input_shape=(config.ROI_IMG_SIZE['HEI...
39,710
async def test_fetch_general_site(hass: HomeAssistant, current_price_api: Mock) -> None: """Test fetching a site with only a general channel.""" current_price_api.get_current_price.return_value = GENERAL_CHANNEL data_service = AmberUpdateCoordinator(hass, current_price_api, GENERAL_ONLY_SITE_ID) result...
39,711
def get_layer_information(cloudsat_filenames, get_quality=True, verbose=0): """ Returns CloudLayerType: -9: error, 0: non determined, 1-8 cloud types """ all_info = [] for cloudsat_path in cloudsat_filenames: sd = SD(cloudsat_path, SDC.READ) if verbose: #...
39,712
def from_magphase(mag_spec, phase, dim: int = -2): """Return a complex-like torch tensor from magnitude and phase components. Args: mag_spec (torch.tensor): magnitude of the tensor. phase (torch.tensor): angle of the tensor dim(int, optional): the frequency (or equivalent) dimension alo...
39,713
def remove_suboptimal_parses(parses: Parses, just_one: bool) -> Parses: """ Return all parses that have same optimal cost. """ minimum = min(parse_cost(parse) for parse in parses) minimal_parses = [parse for parse in parses if parse_cost(parse) == minimum] if just_one: return Parses([minimal_par...
39,714
def local_ranking(results): """ Parameters ---------- results : list Dataset with initial hand ranking and the global hand ranking. Returns ------- results : list Dataset with the initial hand ranking and the game-local hand ranking (from 0 - nplayers). ""...
39,715
def is_monotonic_increasing(bounds: np.ndarray) -> bool: """Check if int64 values are monotonically increasing.""" n = len(bounds) if n < 2: return True prev = bounds[0] for i in range(1, n): cur = bounds[i] if cur < prev: return False prev = cur retur...
39,716
def length(input, min=-1, max=65536): """Filter reads by sequence length""" for read in input: l = read.length if l >= min and l <= max: yield read
39,717
def statistic_image_size(): """ count unique image size """ image_path = "/data/xueruoyao/dataset/road_extraction/deepglobe/segmented/train/gt" # image_path = "/home/xueruoyao/Documents/PythonProgram/dataset/data_aug/gt" image_size_dict: dict = {} print("statistics of image size") with tqdm(tota...
39,718
def parse(data): """ Takes binary data, detects the TLS message type, parses the info into a nice Python object, which is what is returned. """ if data[0] == TLS_TYPE_HANDSHAKE: obj = TlsHandshake() obj.version = data[1:3] obj.length = unpack(">H", data[3:5])[0] if data[5] == TLS_TYPE_CLIENT_HELLO: obj....
39,719
def recoverSecretRanks_GPT(mod_rec, tok_rec, startingText, outInd, finishSentence=True): """ Function to calculate the secret ranks of GPT2 LM of a cover text given the cover text """ startingInd=tok_rec.encode(startingText) endingInd=outInd[len(startingInd):] secretTokensRec=[] for i in ran...
39,720
def threshold_strategies(random_state=None): """Plan (threshold): - [x] aggregated features: (abs(mean - median) < 3dBm) || (2*stdev(x) < 8dBm) - [x] histogram: x < 85dBm - [ ] timeseries batch: p < 10**-3 """ dummy = lambda: dummy_anomaly_injector(scaler=None, random_state=random_s...
39,721
def slice_media(source, destination=None, keep_tags=[], skip_tags=[], duration=None, bitrate='6M', extension='webm', make_separate=True, offset=0, drift=1, audio_only=False): """ take a source (and optional destination) load and set up the other files that will be needed for the desired slice operation...
39,722
def test_relu(): """ Tests ReLU activation class. """ Z = np.array([1, -1, 0]) dA = np.array([2, 3, 5]) expected_A = np.array([1, 0, 0]) expected_dZ = np.array([2, 0, 0]) activation = ReLU() obtained_A = activation.forward(Z) obtained_dZ = activation.backward(dA) np.testin...
39,723
def test_arbitrage_when_bid_notional_less_than_min_notional() -> None: """Should raise `NotionalLessThanMinNotionalError` exception. Bid notional value less than bid min notional value. """ ask = ArbitragePayload( symbol=SymbolInfo( quantity_increment=Decimal("0.01"), fe...
39,724
def _apply_mocks(context: EventContext, handler: EventHandler, event_name: str, effective_events: Dict[str, EventDescriptor], preprocess_hook: Optional[PreprocessHook], postprocess_hook: Optional[PostprocessHook], mock...
39,725
def ellipse_properties(x, y, w): """ Given a the (x,y) locations of the foci of the ellipse and the width return the center of the ellipse, width, height, and angle relative to the x-axis. :param double x: x-coordinates of the foci :param double y: y-coordinates of the foci :param double w: wid...
39,726
def test_normalize_tree(): """ Ensure normalize_tree() wipe off name spaces, prefixes, redundant white spaces and new lines. """ string = """ <data xmlns="http://www.company.com/TOOSchema/BarOS" xmlns:a="http://www.company.com/TOOSchema/BarOS" xmlns:b="http://www.company.co...
39,727
def test_no_feature_category(feature_descriptions, nc_feature): """Testing if None is returned when the feature does not have corresponding category defined.""" fd = FeatureDescriptor(feature_descriptions) assert fd.category(nc_feature) is None
39,728
def build_func(f, build_type): """ Custom decorator that is similar to the @conf decorator except that it is intended to mark build functions specifically. All build functions must be decorated with this decorator :param f: build method to bind :type f: function :parm build_type: The WAF build t...
39,729
def getnumoflinesinblob(ext_blob): """ Get number of lines in blob """ ext, blob_id = ext_blob return (ext, blob_id, int(getpipeoutput(['git cat-file blob %s' % blob_id, 'wc -l']).split()[0]))
39,730
def dir_exists(dir): """Test if dir exists""" return os.path.exists(dir) and os.path.isdir(dir)
39,731
def fetch_data(full_query): """ Fetches data from the given url """ url = requests.get(full_query) # Parse the json dat so it can be used as a normal dict raw_data = url.json() # It's a good practice to always close opened urls! url.close() return raw_data
39,732
def post(*args, **kwargs): # pragma: no cover """Make a post request. This method is needed for mocking.""" return http.post(*args, **kwargs)
39,733
def _AddAlertToGroup(alert_entity, group): """Adds an anomaly to group and updates the group's properties.""" update_group = False if alert_entity.start_revision > group.start_revision: # TODO(qyearsley): Add test coverage. See catapult:#1346. group.start_revision = alert_entity.start_revision update_...
39,734
def shear_x(image: tf.Tensor, level: float, replace: int) -> tf.Tensor: """Equivalent of PIL Shearing in X dimension.""" # Shear parallel to x axis is a projective transform # with a matrix form of: # [1 level # 0 1]. image = transform( image=wrap(image), transforms=[1., level, 0., 0., 1., 0...
39,735
def sequence_data(project_dir, config): """ opens word sequence HDF5 file :param project_dir: :param config: :return: pointer to word sequence array """ try: h5_seq = h5py.File(os.path.join(project_dir, config['files'][config['word_sequence']['file']])) except IOError: lo...
39,736
def extract_const_string(data): """Extract const string information from a string Warning: strings array seems to be practically indistinguishable from strings with ", ". e.g. The following is an array of two elements const/4 v0, 0x1 new-array v0, v0, [Ljava/lang/String; const/4 v1, 0x0 ...
39,737
def choose_action(q, sx, so, epsilon): """ Choose action index for given state. """ # Get valid action indices a_vindices = np.where((sx+so)==False) a_tvindices = np.transpose(a_vindices) q_max_index = tuple(a_tvindices[np.argmax(q[a_vindices])]) # Choose next action based on epsilon-g...
39,738
def _meta_commands(sql: str, context: Context, client: Client) -> Union[bool, Client]: """ parses metacommands and prints their result returns True if meta commands detected """ cmd, schema_name = _parse_meta_command(sql) available_commands = [ ["\\l", "List schemas"], ["\\d?, ...
39,739
def changelog_for_post( post: Dict[str, Any], package_folder: str, uniqifier: str = "" ) -> None: """Requirements for running `safety`""" versions = [] post_id = post["answer_id"] if "answer_id" in post else post["question_id"] # pylint: disable=import-outside-toplevel from so_pip.api_clients.st...
39,740
def soliswets(function, sol, fitness, lower, upper, maxevals, delta): """" Implements the solis wets algorithm """ bias = zeros(delta.shape) evals = 0 num_success = 0 num_failed = 0 dim = len(sol) while evals < maxevals: dif = uniform(0, delta, dim) newsol = clip(so...
39,741
def _get_precision_type(network_el): """Given a network element from a VRP-REP instance, returns its precision type: floor, ceil, or decimals. If no such precision type is present, returns None. """ if 'decimals' in network_el: return 'decimals' if 'floor' in network_el: return 'flo...
39,742
def vtr_command_argparser(prog=None): """ Argument parse for run_vtr_task """ description = textwrap.dedent( """ Runs one or more VTR tasks. """ ) epilog = textwrap.dedent( """ Examples -------- Run the task named 'timing_chain': ...
39,743
def user_list(): """Retrieves a list of the users currently in the db. Returns: A json object with 'items' set to the list of users in the db. """ users_json = json.dumps(({'items': models.User.get_items_as_list_of_dict()})) return flask.Response(ufo.XSSI_PREFIX + users_json, headers=ufo.JSON_HEADERS)
39,744
def md5_str(content): """ 计算字符串的MD5值 :param content:输入字符串 :return: """ m = hashlib.md5(content.encode('utf-8')) return m.hexdigest()
39,745
def test_binsearch(): """ Normal search for plain original algorithm """ arr = [2, 3, 5, 6, 8, 9, 10, 12, 14, 17, 18, 21, 23] rv = bin_search(arr, 14, 0, len(arr)-1) print(rv)
39,746
def hurun_rank(indicator: str = "百富榜", year: str = "2020") -> pd.DataFrame: """ 胡润排行榜 http://www.hurun.net/CN/HuList/Index?num=3YwKs889SRIm :param indicator: choice of {"百富榜", "富豪榜", "至尚优品"} :type indicator: str :param year: 指定年份; {"百富榜": "2015至今", "富豪榜": "2015至今", "至尚优品": "2017至今"} :type ye...
39,747
def test_prepare_headers(): """Check http_headers are correctly prepared.""" s = SoapMessage("endpoint", "method") h = s.prepare_headers({"test1": "one", "test2": "two"}, None) assert h == { "Content-Type": 'text/xml; charset="utf-8"', "test2": "two", "test1": "one", } h ...
39,748
def vocal_recognition_listening(lang="fr-FR"): """ Uses the recognition system and return sentances. @param lang language @return enumerate on tuples (score, text) """ if "ENSAE.Voice" not in sys.modules: if not sys.platform.startswith("win"): rai...
39,749
def yamartino_method(a, axis=None): """This function calclates the standard devation along the chosen axis of the array. This function has been writen to calculate the mean of complex numbers correctly by taking the standard devation of the argument & the angle (exp(1j*theta) ). This uses the Yamart...
39,750
def calc_half_fs_axis(total_points, fs): """ Геренирует ось до половины частоты дискр. с числом точек равным заданному """ freq_axis = arange(total_points)*fs/2/total_points # Hz до половины fs return freq_axis
39,751
def fetch_weather(): """ select flight records for display """ sql = "select station, latitude,longitude,visibility,coalesce(nullif(windspeed,''),cast(0.0 as varchar)) as windspeed, coalesce(nullif(precipitation,''),cast(0.00 as varchar)) as precipitation from (select station_id AS station, info ->> 'Latitude' ...
39,752
def ctemplate(wikidir,tags): """ (str[, str]) -> NoneType Search a Dokuwiki directory (first string) for sub-directories without a 'start.txt', in all these directories create a the start pate, optionally using the second ("quoted") string for the "tags" """ for dirpath, subdirs, files ...
39,753
def update_params(old_param, new_param, errors="raise"): """ Update 'old_param' with 'new_param' """ # Copy old param updated_param = old_param.copy() for k,v in new_param.items(): if k in old_param: updated_param[k] = v else: if errors=="raise": ...
39,754
def UppercaseEnum(*args): """ Provides an :class:`~stem.util.enum.Enum` instance where the values are identical to the keys. Since the keys are uppercase by convention this means the values are too. For instance... :: >>> from stem.util import enum >>> runlevels = enum.UppercaseEnum('DEBUG', 'INFO',...
39,755
def rng_name(): """Generate random string for a username.""" name = "b{dt.second}{dt.microsecond}" return name.format(dt=datetime.datetime.utcnow())
39,756
def collections(id=None): """ Return Collections Parameters ---------- id : STR, optional The default is None, which returns all know collections. You can provide a ICOS URI or DOI to filter for a specifict collection Returns ------- query : STR A query, which can...
39,757
def ajax_upload(): """ handle ajax file upload """ # dropzone sends one ajax request per file, so this invocation is for # one file even if multiple files have been dropped on the web page. page = request.page print_debug(' ajax_upload ') print_debug(' request.form.keys() : {}'.format...
39,758
def seeddb_command(): """Seed the database.""" update_versions() print("Seeded the database.")
39,759
def _create_file(filename: str): """ Create the file filename and create any directories needed Args: filename: Path to the file to be created """ try: os.makedirs(os.path.dirname(filename)) except OSError: pass with open(filename, 'w') as f: f.write('')
39,760
def zmat_to_coords(zmat, keep_dummy=False, skip_undefined=False): """ Generate the cartesian coordinates from a zmat dict. Considers the zmat atomic map so the returned coordinates is ordered correctly. Most common isotopes assumed, if this is not the case, then isotopes should be reassigned to the xyz....
39,761
def get_module_version(module_name: str) -> str: """Check module version. Raise exception when not found.""" version = None if module_name == "onnxrt": module_name = "onnx" command = [ "python", "-c", f"import {module_name} as module; print(module.__version__)", ] ...
39,762
def pd_images(foc_offsets=[0,0], xt_offsets = [0,0], yt_offsets = [0,0], phase_zernikes=[0,0,0,0], amp_zernikes = [0], outer_diam=200, inner_diam=0, \ stage_pos=[0,-10,10], radians_per_um=None, NA=0.58, wavelength=0.633, sz=512, \ fresnel_focal_length=None, um_per_pix=6.0): """ Create a set of simu...
39,763
def add_tickets(create_user, add_flights): """Fixture to add tickets""" user = create_user(USER) tickets = [{ "ticket_ref": "LOS29203SLC", "paid": False, "flight": add_flights[0], "type": "ECO", "seat_number": "E001", "made_by": user, }, { "ticket...
39,764
def test_project_update_view_POST_invalid_payload( django_user_model, supervisor_client, project, project_update_url, payload ): """Test an invalid payload to project update view doesn't update project""" res = supervisor_client.post(project_update_url, payload) updated_project = Project...
39,765
def function(matches): """"yo""" aaaa = 1 index = -1 for match in matches: index += 1 print match
39,766
def compute_depth_errors(gt, pred): """Computation of error metrics between predicted and ground truth depths Args: gt (N): ground truth depth pred (N): predicted depth """ thresh = np.maximum((gt / pred), (pred / gt)) a1 = (thresh < 1.25).mean() a2 = (thresh < 1.25 ** 2).mean() ...
39,767
def sanitize_bvals(bvals, target_bvals=[0, 1000, 2000, 3000]): """ Remove small variation in bvals and bring them to their closest target bvals """ for idx, bval in enumerate(bvals): bvals[idx] = min(target_bvals, key=lambda x: abs(x - bval)) return bvals
39,768
def fetch_engines(): """ fetch_engines() : Fetches documents from Firestore collection as JSON all_engines : Return all documents """ all_engines = [] for doc in engine_ref.stream(): engine = doc.to_dict() engine["id"] = doc.id all_engines.append(engine) ret...
39,769
def check_process_list(): """Looks for update in the process list. To lighten the load, it uses the last modified date. As a side effect, too frequent updates are not possible. """ mtime = os.path.getmtime(os.path.join("data", "process_list.json")) global ptime if ptime < mtime: global p...
39,770
def isone(a: float) -> bool: """Work around with float precision issues""" return np.isclose(a, 1.0, atol=1.0e-8, rtol=0.0)
39,771
async def test_name(hass: HomeAssistant) -> None: """Test the config flow name is copied from registry entry, with fallback to state.""" registry = er.async_get(hass) entity_id = "switch.ceiling" # No entry or state, use Object ID assert wrapped_entity_config_entry_title(hass, entity_id) == "ceilin...
39,772
def get_arguments(): """Get needed options for the cli parser interface""" usage = """DSStoreParser CLI tool. v{}""".format(__VERSION__) usage = usage + """\n\nSearch for .DS_Store files in the path provided and parse them.""" argument_parser = argparse.ArgumentParser( formatter_class=argparse.R...
39,773
def kerr(E=0, U=0, gs=None): """ Setup the Kerr nonlinear element """ model = scattering.Model( omegas=[E]*1, links=[], U=[U]) if gs is None: gs = (0.1, 0.1) channels = [] channels.append(scattering.Channel(site=0, strength=gs[0])) channels.append(scatte...
39,774
def get_estate_urls(last_estate_id: str) -> Dict: """Fetch urls of newly added estates Args: last_estate_id (str): estate_id of the most recent estate added (from last scrape) Returns: Dict: result dict in format {estate_id_1: {estate_url_1}, ... estate_id_N: {estate_url_N}} """ # ...
39,775
def prop_first_step(self, zbackprop): """Velocity-verlet integrator""" if not zbackprop: cbackprop = "" dt = self.get_timestep() else: cbackprop = "backprop_" dt = -1.0 * self.get_timestep() exec("x_t = self.get_" + cbackprop + "positions()") self.compute_elec_struct...
39,776
def increment_version(options): """Increments either release or dev version by 1""" print('current version: %s' % __version__) ver_split = __version__.split('.') dev = options.increment_version.get('dev') if 'dev' in ver_split[-1]: if dev: # If this is already a development versi...
39,777
def check_enemies_bottom(blast_settings, screen, stats, sb, ship, enemies, bullets): """Check if enemies reached bottom""" screen_rect = screen.get_rect() for enemy in enemies.sprites(): if enemy.rect.bottom >= screen_rect.bottom: ship_hit(blast_settings, screen, stats, sb, ...
39,778
def revert_transaction(): """Revert a transaction.""" if not (current_user.is_admin or current_user.is_bartender): flash("You don't have the rights to access this page.", 'danger') return redirect(url_for('main.dashboard')) transaction_id = request.args.get('transaction_id', -1, type=int) ...
39,779
def getinterfacepreference(ctx, # Mandatory main parameter name): """Retrieves an existing cluster interface preference.""" cli_utils.establish_connection(ctx) ctx.logger.info(""": """"""name = """ + str(name)+""";"""+"") try: _GetClusterInterfacePre...
39,780
def is_number(s): """returns true if input can be converted to a float""" try: float(s) return True except ValueError: return False
39,781
def bib_to_string(bibliography): """ dict of dict -> str Take a biblatex bibliography represented as a dictionary and return a string representing it as a biblatex file. """ string = '' for entry in bibliography: string += '\n@{}{{{},\n'.format( bibliography[entry]['type'], ...
39,782
def make_plot(z, figsize=(20, 20), scale=255 * 257, wavelength=800, terrain=None, nir_min=0.2, offset=3.5): """ Make a 3-D plot of image intensity as z-axis and RGB image as an underlay on the z=0 plane. :param z: NIR intensities :param figsize: size of the figure to default ...
39,783
def check_prio_and_sorted(node): """Check that a treap object fulfills the priority requirement and that its sorted correctly.""" if node is None: return None # The root is empty else: if (node.left_node is None) and (node.right_node is None): # No children to compare with ...
39,784
def download100(): """download cifar100 dataset""" if not os.path.exists(IMG_DIR): os.mkdir(IMG_DIR) cifar = CIFAR100(root=IMG_DIR, download=True) return cifar
39,785
async def wait_for_msg(channel): """Wait for a message on the specified Redis channel""" while await channel.wait_message(): pickled_msg = await channel.get() return pickle.loads(pickled_msg)
39,786
def abandoned_baby_bull(high, low, open_, close, periods = 10): """ Abandoned Baby Bull Parameters ---------- high : `ndarray` An array containing high prices. low : `ndarray` An array containing low prices. open_ : `ndarray` An array containing open prices. clos...
39,787
def ngspice_launch(file_loc, working_folder): """Launches NGspice and delete old simulation files from the working_folder""" try: makedirs(working_folder) except OSError: print ("Creation of the directory %s failed" % working_folder) try: for root, dirs, files in os....
39,788
def split_line_num(line): """Split each line into line number and remaining line text Args: line (str): Text of each line to split Returns: tuple consisting of: line number (int): Line number split from the beginning of line remaining text (str): Text for remainder ...
39,789
def rad_to_arcmin(angle: float) -> float: """Convert radians to arcmins""" return np.rad2deg(angle)*60
39,790
def get_tile_prefix(rasterFileName): """ Returns 'rump' of raster file name, to be used as prefix for tile files. rasterFileName is <date>_<time>_<sat. ID>_<product type>_<asset type>.tif(f) where asset type can be any of ["AnalyticMS","AnalyticMS_SR","Visual","newVisual"] The rump is defined as <da...
39,791
def get_indices_by_groups(dataset): """ Only use this to see F1-scores for how well we can recover the subgroups """ indices = [] for g in range(len(dataset.group_labels)): indices.append( np.where(dataset.targets_all['group_idx'] == g)[0] ) return indices
39,792
def ranksumtest(x, y): """Calculates the rank sum statistics for the two input data sets ``x`` and ``y`` and returns z and p. This method returns a slight difference compared to scipy.stats.ranksumtest in the two-tailed p-value. Should be test drived... Returns: z-value for first data set ``...
39,793
def test_pair_coordinates(): """Test for unique coordinates matching.""" set_a = np.array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]) set_b = np.array([[0.1, 0.1], [1.1, 1.1], [2.1, 2.1], [3.1, 3.1], [4.2, 4.2]]) # 4 in set_a and 4, 5 in set B should be unpaired paired, unpaired_a, unpaired_b = pair_c...
39,794
async def create_app(): """ Prepare application """ redis_pool = await aioredis.create_pool(settings.REDIS_CON) middlewares = [session_middleware(RedisStorage(redis_pool)), request_user_middleware] if settings.DEBUG: middlewares.append(aiohttp_debugtoolbar.middleware) # init application ...
39,795
def inchi_to_can(inchi, engine="openbabel"): """Convert InChI to canonical SMILES. Parameters ---------- inchi : str InChI string. engine : str (default: "openbabel") Molecular conversion engine ("openbabel" or "rdkit"). Returns ------- str Canonical SMILES. ...
39,796
def swap(arr: List[T], i: int, j: int) -> List[T]: """Swap two array elements. :param arr: :param i: :param j: :return: """ arr[i], arr[j] = arr[j], arr[i] return arr
39,797
def test_gap_service(central, peripheral): """A GATT peripheral should provide a well formed Generic Attribute Profile service""" connection_handle, _ = gap_connect(central, peripheral) services = central.gattClient.discoverAllServicesAndCharacteristics(connection_handle).result # check that there is ...
39,798
def create_tf_record( article_text: str, output_dir: str, vocabulary_file_path: str, temporary_dir: str, pretraining_data_script_path: str, config_args: argparse.Namespace, no: int ) -> None: """Spawns a subshell and runs script creating tfrecord in it. Function to be called in subprocess. ...
39,799