content
stringlengths
22
815k
id
int64
0
4.91M
def split_loops_into_anchors(file_name): """ Split loops into anchors. """ left = [] right = [] run = file_name.split('.')[0] i = -1 with open(file_name, 'r') as f: for line in f: if '#' in line: # Skip header continue ...
62,700
def read_challenge17_data(db_dir, verbose=False): """ Read the PhysioNet Challenge 2017 data set. @param db_dir: Database directory. @param verbose: Whether to show a progress bar. @return: Tuple of: (array of wfdb records, DataFrame with record ids as index and one hot encoded labels as data). ...
62,701
def create_population(number_of_individual, data_file_name, intervals_min, intervals_max): """ -> Create a population of random initialized individuals """ pack = dichotomization.extract_matrix_from(data_file_name) variable_to_position = pack[1] population = [] for x in range(0, number_of_individual): individ...
62,702
def AdjointOperator(model, geometry, space_order=4, **kwargs): """ Construct an adjoint modelling operator in an tti media. Parameters ---------- model : Model Object containing the physical parameters. geometry : AcquisitionGeometry Geometry object that cont...
62,703
def get_vdi_url(request, compute_id, vname): """ :param request: :param vname: :return: """ compute = get_object_or_404(Compute, pk=compute_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) fqdn = get_hostname_by_ip(compute....
62,704
def munsell_colour_to_xyY(munsell_colour: StrOrArrayLike) -> NDArray: """ Convert given *Munsell* colour to *CIE xyY* colourspace. Parameters ---------- munsell_colour *Munsell* colour. Returns ------- :class:`numpy.ndarray` *CIE xyY* colourspace array. Notes -...
62,705
def get_filter_meta_table(): """Generate a table with meta information about HELP filters This function generates an astropy.table.Table containing the information about the filters used in HELP, except their transmission profile. Returns ------- astropy.table.Table """ # List of fil...
62,706
def test_color_dress(app, login): """ 1. Open page 2. Choose product 3. Open product card 4. Check product colors """ app.page.select_woman_category() app.page.open_product('Printed Summer Dress') assert app.page.product_name() == PrintedSummerDress.name ...
62,707
def corner_subpix(image, corners, window_size=11, alpha=0.99): """Determine subpixel position of corners. Parameters ---------- image : ndarray Input image. corners : (N, 2) ndarray Corner coordinates `(row, col)`. window_size : int, optional Search window size for subpi...
62,708
def adaptive_attack_pgd(model, X, y, c_head_model, scripted_transforms, criterion, epsilon, alpha, attack_iters, restarts, norm, early_stop=False, mixup=False, y_a=None, y_b=None, lam=None, n_views=2, lambda_S=1): """Defense Aware Attack, where the attacker optimizes to both fool the c...
62,709
def login_view(request): """ View that allow us to login a user """ context = {} user = request.user if user.is_authenticated: return redirect("mainpage") if request.method == "POST": form = AccountAuthenticationForm(request.POST) if form.is_valid(): email...
62,710
def rearrange(da, out_dims, in_dims=None, **kwargs): """Wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_. Parameters ---------- da : xarray.DataArray Input DataArray to be rearranged out_dims : list of str, list or dict The output pattern for the dimensions. Th...
62,711
def first(*objects): """ Return the first non-None object in objects. """ for obj in objects: if obj is not None: return obj
62,712
def example_interaction_with_policy(policy="random"): """Example usage of Interaction that uses a random policy or user interaction to decide which candidate to expand. """ assert policy in ("random", "user") def random_policy(state): """Choose a random candidate to expand""" from h...
62,713
def add_gallery_media_pic(): """ POST endpoint that adds a new gallery picture to the club with an image upload and a caption. """ user = get_current_user() json = g.clean_json gallery_pic_file = request.files.get('photo', None) if gallery_pic_file is not None: gallery_pic_url, pi...
62,714
def volume_render( rays_o, rays_d, model: NeuS, obj_bounding_radius=1.0, batched = False, batched_info = {}, # render algorithm config calc_normal = False, use_view_dirs = True, rayschunk = 65536, netchunk = 1048576, white_bkgd = False, near_bypass: Option...
62,715
def toboggan(my_map, location, delta): """ Start tobogganing! Toboggan down the map, starting at location, moving in delta increments, until the edge of the map. Return a list of what was encountered during while tobogganing """ (current_x, current_y) = location (delta_x, delta_y) = delta w...
62,716
def alert_config(*, decoration=None, fd=None, level=None, program=None, syslog_facility=None, syslog_prio=None, reset_defaults=None, timestamps=None): """Reset everything to the specified or default values.""" global cfg if not any(locals().values()) or reset_defaults: ...
62,717
def ball_tree(dataset, profondeur): """ Compartimente dataset selon l'algorithme BallTree. Parameters ---------- dataset : list Liste de points à séparer. profondeur : int Nombre de fois que la liste de départ est séparé. Returns ------- listes : list ...
62,718
def find_all_items(data_type, root_path, debug=False): """ extract all the items in the dir with their label params: root_path <str> output: output_x <list> date_paths iutput: output_y <list> data's label """ output_x = [] output_y = [] _walk_instance = os.walk(root_path) for r...
62,719
def init_list_with_values(list_length: int, init_value): """Return a pre-initialized list. Returns a list of length list_length with each element equal to init_value. init_value must be immutable (e.g. an int is okay; a dictionary is not), or the resulting list will be a list of references to same object (e.g. re...
62,720
def get_ab_test_ci( conversions_control: int, conversions_treatment: int, total_users_control: int, total_users_treatment: int, confidence_level: float = 0.05, ) -> str: """ Conducts an A/B test on the two sided hypothesis: - H_0: Probability of conversion in treatment group minus pr...
62,721
def print_manifest_contents(jar_file_path): """ Prints the contents of the manifest file of the given jar file in dictionary format :param jar_file_path: :return: """ print(get_manifest_contents(jar_file_path))
62,722
def euler_to_quaternion(euler_angles, rotation_order=DEFAULT_ROTATION_ORDER,filter_values=True): """Convert euler angles to quaternion vector [qw, qx, qy, qz] Parameters ---------- * euler_angles: list of floats \tA list of ordered euler angles in degress * rotation_order: Iteratable \t a li...
62,723
def test_incompatible_kit_name_is_not_accepted() -> None: """Test that incompatible kit names are not accepted.""" system_info = KitInfo(name="Astoria Development", version="0.0.0.0dev") bundle_info = load_bundle("valid.toml") bundle_info.kit.name = "Not Astoria Development" with pytest.raises(Inco...
62,724
def histogram(test): """Given a string representing a space separated lowercase letters, return a dictionary of the letter with the most repetition and containing the corresponding count. If several letters have the same occurrence, return all of them. Example: histogram('a b c') == {'a': 1, 'b...
62,725
def make_train_dirs(out_dir): """ Folder structure within the output folder Uses existing folders or creates new ones when there isn't any """ if not os.path.exists(out_dir): os.makedirs(out_dir) if not os.path.exists(os.path.join(out_dir, 'checkpoint')): os.makedirs(os.path.joi...
62,726
def tqdm(iterable=None, desc=None, total=None, leave=True, **kwargs): """ascii=Trueでncols=100なtqdm。""" from tqdm import tqdm as t return t(iterable, desc, total, leave, ascii=True, ncols=100, **kwargs)
62,727
def get_largest_mol(mol_list): """ Given a list of rdkit mol objects, returns mol object containing the largest num of atoms. If multiple containing largest num of atoms, picks the first one. Args: mol_list(list): a list of rdkit mol object. Returns: the largest mol. """ ...
62,728
def decode_sigma(ds,sigma_v): """ ds: Dataset sigma_v: sigma coordinate variable. return DataArray of z coordinate implied by sigma_v """ import re formula_terms=sigma_v.attrs['formula_terms'] terms={} for hit in re.findall(r'\s*(\w+)\s*:\s*(\w+)', formula_terms): terms[hit[0...
62,729
def is_territory(element: inkex.BaseElement) -> bool: """ Checks if the given element is a territory :param element: :return: """ return Warzone.TERRITORY_IDENTIFIER in element.get_id()
62,730
def lowfirst(string): """ Make the first letter of a string lowercase (counterpart of :func:`~django.utils.text.capfirst`, see also :templatefilter:`capfirst`). :param string: The input text :type string: str :return: The lowercase text :rtype: str """ return string and str(string)...
62,731
def get_snapchat_access_token(snap_credentials): """Generate short-lived snapchat access token""" access_url = 'https://accounts.snapchat.com/login/oauth2/access_token' access_params = { 'client_id': snap_credentials['client_id'], 'client_secret': snap_credentials['client_secret'], '...
62,732
def FindSat(ephem, times, gpsweek): # Satloc contains both positions and velocities. """ # Original in ECE456_orbitutils.py. #NOTE: Ask Ashwin for original source # Function to coarse calculate satellite positions given the GPS almanac. # The calculation can be performed for multiple satellites with...
62,733
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" xml = dumps(data) # simplexml lacks ability to insert encoding and standalone, # so this is a hack xml_with_headers = "%s%s%s" % (xml[0:20], 'encoding="utf-8" standalone=...
62,734
def plot_box(points_horizon, img_obj): """ Based on the crosspoints to extract the grids :param points_horizon: horizon crosspoints :param img_obj: the class of img :return: """ #########################################################################################################...
62,735
def priority(profile): """ function : to set priority level based on certain age group input : id, age, infection_status (0 means not infected , 1 means infected) , coordinates, residency output : priority level : local_high(6), local_medium(5) , local_low (4), foreign(3), foreign(2) ,foreign(1)...
62,736
def _compile1_next_statement_with_mods(statements: Sequence[Statement]) -> (IFElement, int): """Returns the IFElements and the number of statements read""" main_statement = statements[0] if main_statement.matches_pattern(TEXT_PATTERN): ifelement = IFText(main_statement.get_atoms()[2].get_value()) ...
62,737
def build_selection(stage_name, config, weights=[]): """Creates event selectors based on the configuration. Parameters: stage_name: Used to help in error messages. config: The event selection configuration. weights: How to weight events, used to produce the resulting cut eff...
62,738
def seqlib_type(cfg): """ Get the type of :py:class:`~enrich2.seqlib.SeqLib` derived object specified by the configuration object. Args: cfg (dict): decoded JSON object Returns: str: The class name of the :py:class:`~seqlib.seqlib.SeqLib` derived object specified by `cfg`...
62,739
def fetch_inventory(app: Sphinx, uri: str, inv: Any) -> Any: """Fetch, parse and return an intersphinx inventory file.""" # both *uri* (base URI of the links to generate) and *inv* (actual # location of the inventory file) can be local or remote URIs localuri = '://' not in uri if not localuri: ...
62,740
def ids(probabilities): """Turn a 1-hot encoding or a probability distribution over the possible characters back into its (most likely) character representation.""" return [str(c) for c in np.argmax(probabilities, 1)]
62,741
def scrape(start=None, end=None, silent=False): """Returns a pandas DataFrame of school information extracted from the website CollegeData.com, with each row corresponding to a successfully scraped schoolId in the range [start, stop], inclusive, with each column corresponding to labeled information fiel...
62,742
def clean_pdb(traj,neighbour_cutoff=5.0,Nsigma=1): """ pdb_clean """ print("Initial number of atoms ",traj.n_atoms) traj.superpose(traj, 0) atom_indices = pdb_clean_get_atom_indices(traj,neighbour_cutoff=neighbour_cutoff,Nsigma=Nsigma) traj.atom_slice(atom_indices,inplace=True) traj.superpos...
62,743
def modules( adata: AnnData, root_milestone: str, milestones: Iterable, layer: Optional[str] = None, module: Literal["early", "late", "all"] = "all", ): """\ Extract mean expression of identified early and late modules. Parameters ---------- adata Annotated data matrix. ...
62,744
def parse_args(): """ define and parse command line arguments. """ desc = 'Compare the performance of the C version of libexpat to Rust port.' parser = argparse.ArgumentParser(description=desc) # parser.add_argument('-c', '--clean-all', default=False, # action='store_true...
62,745
def largest_pandigital_multiples(): """ This function returns the largest pandigital number which is a multiple of an integer and a sequence of integer (1,2,3,..n) """ largest_number = 0 for i in range(1, 50000): j = 1 number = i*j while len(str(number)) < 9: ...
62,746
def assemble(ctx, layers, tags_to_names, output): """Create the full image from the list of layers.""" layers = [l["layer"] for l in layers] args = [ "--output=" + output.path, ] + [ "--tags=" + tag + "=@" + tags_to_names[tag].path for tag in tags_to_names ] + ["--layer=" + l...
62,747
def train(unimodal_files, rep_size, classes, sub_sizes, train_data, valid_data, surrogate, max_labels, batch_size=32, epochs=3, search_iter=3, num_samples=15, epoch_surrogate=50, eta_max=0.001, eta_min=0.000001, Ti=1, Tm=2, temperature_init=10.0, temperature_final=0.2, temperatur...
62,748
def test_pickle(): """Check pickability.""" import pickle # Random forest obj = RandomForestClassifier(random_state=0) obj.fit(iris.data, iris.target) score = obj.score(iris.data, iris.target) s = pickle.dumps(obj) obj2 = pickle.loads(s) assert_equal(type(obj2), obj.__class__) ...
62,749
def parentdir(p, n=1): """Return the ancestor of p from n levels up.""" d = p while n: d = os.path.dirname(d) if not d or d == '.': d = os.getcwd() n -= 1 return d
62,750
def plot_kdeplot(data, ylabel, title, log_scaling=True): """ Args: data: Dict of list of numbers. """ fig, ax = plt.subplots(1, 1, figsize=(8, 6), dpi=300) plt.xticks(rotation=90) d = [] for k, v in data.items(): for i in v: d.append((k, i)) df = pd.DataFrame...
62,751
def get_sector_symbol_name_url(): """ 获取期货所对应板块的 URL :return: dict {'能源': '/commodities/energy', '金属': '/commodities/metals', '农业': '/commodities/softs', '商品指数': '/indices/commodities-indices'} """ url = "https://cn.investing.com/commodities/" res = requests.post(url, headers=sho...
62,752
def test_extensions(nlp, read): """ Values obtained by manual calculation. """ nlp.add_pipe(read, last=True) doc = nlp("I contain four words. Therefore, it should be possible to calculate by hand.") syllable_result = { "i": 1, "contain": 2, "four": 1, "words": 1, ...
62,753
def visualize(mesh, vector_field, colors=None, params=None): """ Visualize a mesh and a vector field over it :param mesh: a mesh with n points :param vector_field: (n,3) array :param colors: (n,3) array :param params: params[0] is the length of the quivers :return: """ n = mesh.verti...
62,754
async def test_set_plate_temp( subject: driver.ThermocyclerDriverV2, connection: AsyncMock, temp: float, hold_time: Optional[float], volume: Optional[float], expected_body: str, ) -> None: """It should send a set plate temperature command.""" await subject.set_plate_temperature(temp=temp...
62,755
def log__OperationsEvent( ctx, event_type_id, event_payload_dict=None, dbOperationsEvent_child_of=None, timestamp_event=None, ): """ creates a OperationsEvent instance if needed, registers it into the ctx """ # defaults # timestamp overwrite? timestamp_event = timestamp_e...
62,756
def parameter_getExpressionReferences(limitingNodes=None, excludeSelfRefs=True): """ getExpressionReferences(limitingNodes=None, excludeSelfRefs=True) -> {node: set(nodes)} Get a map of all expressions references. Looks for getNode or getParam. @see getReferences(time) @param limitingNodes if not No...
62,757
def bare_rate_theta(k, kp, Ntheta, N_z): """ Calculate phonon scattering rate matrix element (scattering rate without thermal factors NQ of NQ+1) vs scattering angle theta ***for a given pair*** of k and k'. k magnitude of initial vector kp magnitude of scattering vector k' Ntheta number ...
62,758
def ingest_data(args): """ Ingest and wrangle data from BLS """ conf = get_config() opts = dict(vars(args)) del opts['func'] opts['startyear'] = opts.pop('start_year') or conf.STARTYEAR opts['endyear'] = opts.pop('end_year') or conf.ENDYEAR record = ingest(**opts) return ( ...
62,759
def decode(loc, priors, variances=[0.1, 0.2]): """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc (tensor): location predictions for loc layers, Shape: [num_priors,4] priors (tensor): Prior boxes in center-...
62,760
def conv2dconv2d( shape_input, pad1, stride1, dilation1, shape_filter1, pad2, stride2, dilation2, shape_filter2, k_split_factor, h_split_factor, dtype, storage_scope="global", ): """ Conv2d -> Conv2d wherein the input activation is defined by its logical N...
62,761
def form(title='', text='', cancel_text='Cancel', inputs=[], buttons=[], style=None, async_=False): """ Display a text input box. Return the given text, or None when cancelled. """ #def accept(): # get_app().layout.focus(ok_button) input_objects = [] button_objects = [] def creat...
62,762
def process_file(filepath): """ decides to either call process_openxml or process_ole """ if olefile.isOleFile(filepath): return process_ole(filepath) else: return process_openxml(filepath)
62,763
def test_continue_statement(): """CONTINUE statement @see: https://docs.python.org/3/tutorial/controlflow.html The continue statement is borrowed from C, continues with the next iteration of the loop. """ # This list will contain only even numbers from the range. even_numbers = [] # This ...
62,764
def run(*args): """ Create admin using this command. If the email already is registered, just return the email and no need to create new users. """ if args and "email" in args[0]: email = args[0].split("=")[1] admin = User.objects.get_user(email=email) if admin: prin...
62,765
def main(set_collection=False, add=False, generate_stream=False, stream=False, stop=False): """ :param stop: :param set_collection: :param add: :param generate_stream: :param stream: :return: """ collection_id = 'Collection' bucket_id = 'ppkbvisitorvault' photo_id = 'param.j...
62,766
def read_data(data_path): """Read real-world trial data from given folder Arguments: data_path (string): path to folder containing measurements.csv and transforms.csv files to be read in Returns: (tuple of arrays): measurements array and transforms array populated with data fro...
62,767
def get_rms(y): """ Compute the root mean square of an array, usually a Y array. Parameters ---------- y (vector array): Array of values where the variance needs to be computes. Returns ------- RMS (value): The RMS value. """ return np.sqrt(np.mean(y ** 2.0))
62,768
def symmetric_phase_corr(I1, I2): """ match two imagery through symmetric phase only correlation (SPOF) also known as Smoothed Coherence Transform (SCOT) Parameters ---------- I1 : numpy.array, size=(m,n), ndim={2,3} array with intensities I2 : numpy.array, size=(m,n), ndim={2,3} ...
62,769
def splitImage (newDir, imgToSplit, imgToSplitDir, oldMatchLocations): """ :type newDir: The name of the new directory. :type imgToSplit: The name of the image that needs to be cropped. :type imgToSplitDir: The name of the directory of the image that needs to be cropped. :type oldMatchLocations: The previous matc...
62,770
def unique_recid(data, dataname): """ Test that RECID values are unique. """ recid = data["RECID"] unique, counts = np.unique(recid, return_counts=True) recid_count = dict(zip(unique, counts)) duplicates = False msg = "" for rid in sorted(recid_count.keys()): if recid_count[r...
62,771
def run(): """ The entry function of the script. This finds existing materials on FBX objects, converts to Stingray materials, and assigns corresponding textures. :return: """ file_name = pm.sceneName() base_directory = os.path.dirname(pm.sceneName()) print('Base Directory: {}'.format(ba...
62,772
def vessel_kml( env, vessels, fname="vessel_movements.kml", icon="http://maps.google.com/mapfiles/kml/shapes/sailing.png", size=1, scale=1, stepsize=120, ): """Create a kml visualisation of vessels. Env variable needs to contain epoch to enable conver...
62,773
def saturated_oxygen(t,s,gsw=False): """Compute oxygen saturation from temperature and salinity Oxygen saturation value is the volume of oxygen gas absorbed from humidity-saturated air at a total pressure of one atmosphere, per unit volume of the liquid at the temperature of measurement (ml/l) """ ...
62,774
def get_cpe_version(cpe): """ Determine if the given CPE name is following version 2.2 or 2.3 of the standard. :param cpe: CPE name. :type cpe: str :returns: CPE standard version ("2.2" or "2.3"). :rtype: str """ if not isinstance(cpe, basestring): raise TypeError("Expected...
62,775
def PaddingMask(pad=0): """Returns a layer that maps integer sequences to padding masks. The layer expects as input a batch of integer sequences. The layer output is a tensor that marks for each sequence position whether the integer (e.g., a token ID) in that position represents padding -- value `pad` -- versu...
62,776
def read_local_rib(G, curr, prefix, port=0): """ Read local rib and return the next hop of a prefix. Return None if it doesn't have hop. """ # FIXME: This function is duplicate with default_routing_policy() in route.py local_rib = G.node[curr]['rib'] ribs_in = G.node[curr]['adj-ribs-in'] if ...
62,777
def parseXML(user, fname): """ Read 1 XML file via remote client and parse the content. """ data = localFs.read_user_file(user, fname) try: return etree.fromstring(data) except Exception as e: logError('Error parsing file `{}`, for user `{}`: `{}`!'.format(fname, user, e)) ...
62,778
def get_libraries_names(): """ Returns names of elements, for which are installed packages from PMDK library. """ rpm_packages_path = path.join(PMDK_PATH, 'rpm', SYSTEM_ARCHITECTURE) libraries_names = [elem.split('-')[0] for elem in listdir(rpm_packages_path) if PMDK_VERSI...
62,779
def update_library_version(version: str, root_dir: str): """ Rewrites all metadata files in ./samples/generated to the version number argument """ root_dir_path = Path(root_dir) snippet_metadata_files = get_sample_metadata_files(root_dir_path) for file in snippet_metadata_files: with o...
62,780
def rfactorial(n: int) -> int: """Recursive factorial function :param n: .. docstring::python >>> from math import factorial >>> rfactorial(1) == factorial(1) True >>> rfactorial(2) == factorial(2) True >>> rfactorial(3) == factorial(3) True ...
62,781
def vassign(configuration, threads = 0): """ Loads network configuration (user characteristics, network capacity, representations, etc. from a scenario file and solves the ILP. """ # num users N = len(configuration["users"]) # Capacity in terms of pRBs capacity = configuration["nprb"] # num representa...
62,782
def extract_port_vlan(strValue): """处理show port vlan得到的数据 Args: strValue (str): show port vlan得到的数据 Returns: list: 元组列表。形式如,[(startVlan, endVlan, "U"), [(startVlan, endVlan, "T"),...]。 """ # port 9:2, # vlan(optin): # 1000(U) . # 1251 ~ 1254(T). # 3049 ~ 3049(T). ...
62,783
def num_sort(new_num, old_num, list_data, old_data): """修改排序,自动按新旧序号重新排列""" if old_data not in list_data: old_data.num = len(list_data) + 1 else: _temp_data = list_data.pop(list_data.index(old_data)) list_data.insert(new_num - 1, _temp_data) if old_num == new_num: ...
62,784
def construct_version_info(): """Make version info using git. Parameters ---------- None Returns ------- version_info : dict Dictionary containing version information as key-value pairs. """ hera_opm_dir = os.path.dirname(os.path.realpath(__file__)) def get_git_output...
62,785
def augment_dim(x3: Array, w: Array) -> Array: """(x,y,z) -> (x,y,z,w)""" d4 = np.expand_dims(w, axis=-1) x4 = np.concatenate((x3, d4), axis=1) assert len(x4) == len(x3) assert x4.shape[1] == 4 return x4
62,786
def create_model_and_store_checkpoint(config: ModelConfigBase, checkpoint_path: Path) -> None: """ Creates a Lightning model for the given model configuration, and stores it as a checkpoint file. If a GPU is available, the model is moved to the GPU before storing. The trainer properties `current_epoch` ...
62,787
def shorten_reference_string(reference_string): """Shorten a reference string Returns the minimum necessary string to unambigiously list references: E.g. `Genesis 1, Genesis 2` -> `Genesis 1, 2` """ range_list = parse_reference_string(reference_string) if len(range_list) == 0: return ""...
62,788
def get_battery_percentage() -> int: """整机剩余电量,返回0-100的整数""" pass
62,789
def test_with_one_item(): """Checks that the batcher works with one Item.""" title = "foo" metadata = {"summary": "bar", "tests": "baz"} expected_title = "[1/1] foo" items = [Item(key="foo.py")] batcher = ChunkBatcher(title=title, metadata=metadata, chunk_size=10) check_batcher(batcher, ite...
62,790
def many2many_dicts(m2mlist): """ Maps objects from one list to the other list and vice versa. Args: m2mlist: list of 2lists [list1i, list2i] where list1i, list2i represent a many to many mapping Returns: (one2two, two2one) : one2two, two2one dictionaries from elements o...
62,791
def can_read_members(user: QfcUser, organization: Organization) -> bool: """Return True if the `user` can list members (incl. teams) of `organization`. Return False otherwise.""" if not organization.is_organization: return False return True
62,792
def total_variation_loss(x, img_size): """ This function computes the total variation loss as an additional loss to the content and style loss from the paper "A Neural Algorithm of Artistic Style". Args: x [numpy.ndarray] generated image with index axis as first dimension. Returns: tota...
62,793
def read_mat_ark(file_or_fd,output_folder): """ generator(key,mat) = read_mat_ark(file_or_fd) Returns generator of (key,matrix) tuples, read from ark file/stream. file_or_fd : scp, gzipped scp, pipe or opened file descriptor. Iterate the ark: for key,mat in kaldi_io.read_mat_ark(file): ... Read ...
62,794
def test_get_annotations_data_returned( pandas_series, coordination_args, monkeypatch ): """Test coordination of annotation retrieval for a given protein.""" def mock_get_anno(*args, **kwargs): annotations = [["NA", "NA", "NA", "NA", "NA"]] return annotations monkeypatch.setattr(get_ge...
62,795
def _readfile(dirpath, filename): """ Read a complete file and return content as a unicode string, or empty string if file not found """ try: with codecs.open(os.path.join(dirpath, filename), "r", "utf-8") as f: return f.read() except IOError: return u""
62,796
def _handle_saved_query_response(response): """ Handle saved query response, check whether there are multiple entities in the response or not :param response: """ if response.json().get('saved_queries'): queries = response.json()['saved_queries'] for query in queries: _pr...
62,797
def args_readfactors(lst): """Parse the factor arguments.""" factors = dict() if lst: for s in lst: res = s.partition('=') if not res[0]: raise CGBadArg("Factor has no key.") if not res[2]: raise CGBadArg("Factor has no value.") factors[res[0]] = float(res[2]) return factors
62,798
def Adimensional_to_Asquare(SII,Z_jct,Te): """ Converts a SII with no unit to A**2/Hz """ return (2.0*_kb*Te)*SII/Z_jct
62,799