content
stringlengths
22
815k
id
int64
0
4.91M
def _scale_pot(pot, scale_coeff, numtors): """ Scale the potential """ print('scale_coeff test 0:', scale_coeff, numtors) scale_factor = scale_coeff**(2.0/numtors) print('scale_coeff test:', scale_coeff, numtors, scale_factor) new_pot = {} for idx, val in pot.items(): new_pot[i...
44,600
def get_substation_file(): """Return the default substation file for the CONUS.""" return pkg_resources.resource_filename('cerf', 'data/hifld_substations_conus_albers.zip')
44,601
def check_finite_Dataset(ds): """Check Dataset does not contain NaN and Inf values.""" # Check is a Dataset if not isinstance(ds, xr.Dataset): raise TypeError("'ds' must be an xarray Dataset.") # Check no NaN values ds_isnan = xr.ufuncs.isnan(ds) list_vars_with_nan = [] flag_raise_...
44,602
def configure_assignment_caller(context, pyramid_request, parsed_params=None): """ Call BasicLTILaunchViews.configure_assignment(). Set up the appropriate conditions and then call BasicLTILaunchViews.configure_assignment(), and return whatever BasicLTILaunchViews.configure_assignment() returns. ...
44,603
def hpat_pandas_series_isna(self): """ Pandas Series method :meth:`pandas.Series.isna` and :meth:`pandas.Series.isnull` implementation. .. only:: developer Test: python -m sdc.runtests sdc.tests.test_series.TestSeries.test_series_isna1 Test: python -m sdc.runtests sdc.tests.test_series.Tes...
44,604
def _filter_stmts(base_node: nodes.NodeNG, stmts, frame, offset): """Filter the given list of statements to remove ignorable statements. If base_node is not a frame itself and the name is found in the inner frame locals, statements will be filtered to remove ignorable statements according to base_node'...
44,605
def lcp_coordinate_conversion(start_coords,end_coords,crs,transform): """ Simple Example: network = lcp.create_raster_network(array) Parameters: - 'start_coords' is a list of tuples (lon,lat) - 'end_coords' is a list of lists of tuples. Each list of end points corresponds to a...
44,606
def create_large_map(sharing_model): """ Create larger map with 7 BS that are arranged in a typical hexagonal structure. :returns: Tuple(map, bs_list) """ map = Map(width=230, height=260) bs_list = [ # center Basestation('A', Point(115, 130), get_sharing_for_bs(sharing_model, 0)...
44,607
def np_scatter_add(input,axis,index,src): """ numpy wrapper for scatter_add """ th_input = th.as_tensor(input,device="cpu") th_index = th.as_tensor(index,device="cpu") th_src = th.as_tensor(src,device="cpu") dim = axis th_output = th.scatter_add(th_input,dim,th_index,th_src) output = th_output.numpy() return o...
44,608
def _file_gunzipper(id_list: List[str], genomes_metadata: pd.DataFrame, genomes_directory: str) -> None: """Unzips the .gz file corresponding to each id in id_list""" for id_ in id_list: filename = get_zipped_fasta_name(id_, genomes_metadata) fna_gz_filen...
44,609
def netmiko_connect(device_name, device): """ Successful connection returns: (True, connect_obj) Failed authentication returns: (False, None) """ hostname = device["host"] port = device.get("port", 22) msg = "" try: net_connect = ConnectHandler(**device) msg = f"Netmiko...
44,610
def get_tracer(request): """ Utility function to retrieve the tracer from the given ``request``. It is meant to be used only for testing purposes. """ return request['__datadog_request_span']._tracer
44,611
async def stdio(loop=None): """Set up stdin/stdout stream handlers""" if loop is None: loop = asyncio.get_event_loop() reader = asyncio.StreamReader() reader_protocol = asyncio.StreamReaderProtocol(reader) writer_transport, writer_protocol = await loop.connect_write_pipe(FlowControlMixin, ...
44,612
def local_self_attention_layer(hparams, prefix): """Create self-attention layer based on hyperparameters.""" return transformer_layers.LocalSelfAttention( num_heads=hparams.get(prefix + "num_heads"), num_memory_heads=hparams.get(prefix + "num_memory_heads"), radius=hparams.local_attention_radius, ...
44,613
def hwtrain(X_csv: str, y_csv: str, model: str = 'lm') -> str: """ Read the feature matrix and label vector from training data and fit a machine learning model. The model is saved in pickle format. Parameters ---------- X_csv The path to the feature matrix in CSV fo...
44,614
def convert_ban_to_quan(str_ban): """半角转全角""" str_quan = "" for uchar in str_ban: inside_code = ord(uchar) if inside_code == 32: #半角空格直接转化 inside_code = 12288 elif inside_code >= 32 and inside_code <= 126: #半角字符(除空格...
44,615
def update_user_permissions(userid, profile="grafana", **kwargs): """ Update a user password. userid Id of the user. isGrafanaAdmin Whether user is a Grafana admin. profile Configuration profile used to connect to the Grafana instance. Default is 'grafana'. CL...
44,616
def main(ctx, wind_h5, out_dir, compute_tree, verbose): """ WindX Command Line Interface """ ctx.ensure_object(dict) ctx.obj['H5'] = wind_h5 ctx.obj['OUT_DIR'] = out_dir ctx.obj['CLS_KWARGS'] = {'compute_tree': compute_tree} multi_h5_res, hsds = check_res_file(wind_h5) if multi_h5_r...
44,617
def to_xepsilon(_): """ :param _: :return: """ return xepsilon()
44,618
def build_permissions_response(): """ Build a response containing only speech """ output = "I'm sorry, I was not able to lookup your home town. "\ "With your permission, I can provide you with this information. "\ "Please check your companion app for details" return { 'outp...
44,619
def simple_tokenizer(text): """ Example for returning a list of terms from text. 1. Normalizes text by casting to lowercase. 2. Removes punctuation from tokens. 3. Returns tokens as indicated by whitespace. """ text = text.lower() # Remove punctuation from file if isinstance(te...
44,620
def progress(*args, **kwargs): """ The HTML <progress> Element is used to view the completion progress of a task. While the specifics of how it's displayed is left up to the browser developer, it's typically displayed as a progress bar. Javascript can be used to manipulate the value of progress ...
44,621
def unfollow(user, obj, send_action=False): """ Removes a "follow" relationship. Set ``send_action`` to ``True`` (``False is default) to also send a ``<user> stopped following <object>`` action signal. Example:: unfollow(request.user, other_user) """ from actstream.models import F...
44,622
def openssl_error(): """Return the OpenSSL error type for use in exception clauses""" return _OpenSSLError
44,623
def load_path(path, visitor=TokenVisitor): """ Args: path (str): Path to file to deserialize visitor (type(TokenVisitor)): Visitor to use Returns: (list): Deserialized documents """ with open(path) as fh: return deserialized(Scanner(fh), visitor)
44,624
def get_card_names(cards): """ :param cards: List of card JSONs :return: List of card names (str) """ names = [] for card in cards: name = card.get("name") names.append(name) return names
44,625
def write_gzipped_graph(graph: nx.MultiDiGraph, path: str) -> None: """Write a graph as gzipped nodelink.""" with gzip.open(path, 'wt') as file: json.dump(nx.node_link_data(graph), file)
44,626
def pyversion(ref=None): """Determine the Python version and optionally compare to a reference.""" import platform ver = platform.python_version() if ref: return [ int(x) for x in ver.split(".")[:2] ] >= [ int(x) for x in ref.split(".")[:2] ] else: ret...
44,627
def opt_tqdm(iterable): """ Optional tqdm progress bars """ try: import tqdm except: return iterable else: return tqdm.tqdm(iterable)
44,628
def get_dataset_config(): """Gets the config for dataset.""" config = config_dict.ConfigDict() # The path to the specification of grid evaluator. # If not specified, normal evaluator will be used. config.grid_evaluator_spec = '' # The directory of saved mgcdb84 dataset. config.dataset_directory = '' # T...
44,629
def compile_expr(exp: Expr, defns: List[Defn], si: int, env: Env) -> List[Instr]: """Generates instructions for a given expression, at a given stack index, and in a given environment""" raise NotImplementedError("compile_expr")
44,630
def test_Transpose_3dsignal(par): """Dot-test and adjoint for Transpose operator for 3d signals """ dims = (par['ny'], par['nx'], par['nt']) x = np.arange(par['ny']*par['nx']*par['nt']).reshape(dims) + \ par['imag'] * np.arange(par['ny']*par['nx']*par['nt']).reshape(dims) Top = Transpose(di...
44,631
def stub_multiservo_yaml(tmp_path: pathlib.Path) -> pathlib.Path: """Return the path to a servo config file set up for multi-servo execution.""" config_path: pathlib.Path = tmp_path / "servo.yaml" settings = tests.helpers.BaseConfiguration() measure_config_json = json.loads( json.dumps( ...
44,632
def _escape_space(program): """escape spaces in for windows""" if os.name == "nt" and ' ' in program: return '"' + program + '"' else: return program
44,633
def rename_internal_nodes(tree, pg_dict): """Rename internal nodes (add phylogroups to the name). """ numbers = collections.defaultdict(lambda: 0) for node in tree.traverse("postorder"): if node.is_leaf(): continue pgs = node_to_pg(node, pg_dict) pgs_s = "-".join(so...
44,634
def test_initialize_users(mock_config): """Verify that you can list parameters.""" with patch( "axis.vapix.session_request", return_value="""users="userv" viewer="userv" operator="usera" admin="usera" ptz= """, ) as mock_request: vapix = Vapix(mock_config) vapix.initialize_us...
44,635
def test_ap_hs20_3gpp_constraints(dev, apdev): """Hotspot 2.0 connection and 3GPP credential constraints""" bssid = apdev[0]['bssid'] params = hs20_ap_params() params['hessid'] = bssid params['anqp_3gpp_cell_net'] = "555,444" params['domain_name'] = "wlan.mnc444.mcc555.3gppnetwork.org" param...
44,636
def assign_by_euclidian_at_k(X, T, k): """ X : [nb_samples x nb_features], e.g. 100 x 64 (embeddings) k : for each sample, assign target labels of k nearest points """ # distances = sklearn.metrics.pairwise.pairwise_distances(X) chunk_size = 1000 num_chunks = math.ceil(len(X)/chunk_s...
44,637
def _svd_classification(dataset='mnist_small'): """ svd on classificaiton dataset Inputs: dataset: (str) name of dataset Outputs: accuracy on predicted values """ if dataset=='rosenbrock': x_train, x_valid, x_test, y_train, y_valid, y_test = load_dataset('rosenbrock', n...
44,638
def set_answer(set_number): """ get result answer >>> set_answer(600851475143) 6857 >>> set_answer(3000) 5 """ while True: prime_fac = prime_factorization(set_number) if prime_fac < set_number: set_number //= prime_fac else: return set_numb...
44,639
def model_infer(model, test_images, test_affinities, test_beliefs, args): """ Parameters: model: object with the trained model test_images: batch of images (float32), size: (test_batch_size,3,x,y) test_affinities: batch of affinity maps (float32), size: (test_batch_size,16,x/8,y/8) test_beliefs:...
44,640
def clean_value(value, suffix): """ Strip out copy suffix from a string value. :param value: Current value e.g "Test Copy" or "test-copy" for slug fields. :type value: `str` :param suffix: The suffix value to be replaced with an empty string. :type suffix: `str` :return: Stripped string wit...
44,641
def list_devices_to_string(list_item): """Convert cfg devices into comma split format. Args: list_item (list): list of devices, e.g. [], [1], ["1"], [1,2], ... Returns: devices (string): comma split devices """ return ",".join(str(i) for i in list_item)
44,642
def make_orientation_meeting(doc, method): """Create an orientation meeting when a new user is added""" meeting = frappe.get_doc({ "doctype":"Meeting", "title":"Orientation for {0}".format(doc.first_name), "date": add_days(nowdate(),1), "from_time":"09:00", "to_time":"09:30", "status":"Planned", "attend...
44,643
def test_shape_initialized_with_no_shapeid_field_should_pass_for_now(): """Shape initialized with no shapeID will use default shapeID.""" config_dict = dict() config_dict["default_shape_identifier"] = "default" shap = TAPShape() shap.sc_list = [] shap.sc_list.append({"propertyID": "dct:creator",...
44,644
def trace_module(no_print=True): """ Trace plot series module exceptions """ mname = 'series' fname = 'plot' module_prefix = 'putil.plot.{0}.Series.'.format(mname) callable_names = ( '__init__', 'data_source', 'label', 'color', 'marker', 'interp', 'li...
44,645
def fill_between(xdata, lb, ub, xlabel='', ylabel='', alpha=0.3, color=None): """Fill between lines. Parameters ---------- xdata : |ndarray| X values of points to plot. Should be vector of length ``Nsamples``. lb : |ndarray| Lower Y vaules to plot. Should be of size ``(Nsamples,.....
44,646
def get_ids(values): """Transform numeric identifiers, corpora shortcodes (slugs), and two-letter ISO language codes, into their corresponding numeric identifier as per the order in CORPORA_SOURCES. :return: List of indices in CORPORA_SOURCES :rtype: list """ if "all" in values: ids...
44,647
def quiet_option(func): """Add a quiet option.""" def _callback(ctx, unused_param, value): _set_verbosity(ctx, -value) return value return click.option('-q', '--quiet', count=True, expose_value=False, help='Decreases verbosity.', callback=_cal...
44,648
def _compute_gaussian_fwhm(spectrum, regions=None): """ This is a helper function for the above `gaussian_fwhm()` method. """ fwhm = _compute_gaussian_sigma_width(spectrum, regions) * gaussian_sigma_to_fwhm return fwhm
44,649
async def sorted( iterable: AnyIterable[T], *, key: Optional[Callable[[T], Any]] = None, reverse: bool = False, ) -> List[T]: """ Sort items from an (async) iterable into a new list The optional ``key`` argument specifies a one-argument (async) callable, which provides a substitute for ...
44,650
def config_split(config): """ Splits a config dict into smaller chunks. This helps to avoid sending big config files. """ split = [] if "actuator" in config: for name in config["actuator"]: split.append({"actuator": {name: config["actuator"][name]}}) del(config["actua...
44,651
def test_utils_top_level_imports(): """Test Top-Level Imports.""" # First test they exist subpkg: str for subpkg in utils.__all_top_imports__: assert hasattr(utils, subpkg) # Next test that top-levels are all the possible top-levels drct: str = os.path.split(utils.__file__)[0] # direct...
44,652
def test_eq(): """Schedule == Schedule -> bool""" schedule_a = Schedule([ TimeRange(Time(1000), Time(2000)) ]) schedule_b = Schedule([ TimeRange(Time(1000), Time(2000)) ]) schedule_c = Schedule([ TimeRange(Time(1500), Time(2500)) ]) assert schedule_a == schedule_b...
44,653
def test_cve_id_cve_age(config, javascript_cve, mocker): """Test scenario when both `cve_id` and `cve_age` options are set.""" # cve_age='1': CVE is older, but the check should be excluded automatically mocker.patch('cvejob.filters.input.Config', config(cve_id='CVE-2018-3757', cve_age='1')) assert vali...
44,654
def transl(x, y=None, z=None): """ Create or decompose translational homogeneous transformations. Create a homogeneous transformation =================================== - T = transl(v) - T = transl(vx, vy, vz) The transformation is created with a unit rotation...
44,655
def find_next_square2(sq: int) -> int: """ This version is just more compact. """ sqrt_of_sq = sq ** (1/2) return -1 if sqrt_of_sq % 1 != 0 else int((sqrt_of_sq + 1) ** 2)
44,656
def log_info(msg): """log an info message""" print colored('INFO', 'blue'), msg if ukconfig.LOG_DIR: with open(os.path.join(ukconfig.LOG_DIR, 'info.txt'), 'a') as f: f.write(msg) f.write('\n') # TODO: use log util, log to file, including time, module, etc.
44,657
def hex_2_hsv(hex_col): """ convert hex code to colorsys style hsv >>> hex_2_hsv('#f77f00') (0.08569500674763834, 1.0, 0.9686274509803922) """ hex_col = hex_col.lstrip('#') r, g, b = tuple(int(hex_col[i:i+2], 16) for i in (0, 2 ,4)) return colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0)
44,658
def _drivers_dir() -> str: """ ドライバ格納ディレクトリのパスを返します :return: ドライバ格納ディレクトリのパス """ return str(Path(__file__).absolute().parent.parent.joinpath('drivers'))
44,659
def bootstrap(user='julython'): """Install packages and docker on a new host.""" sudo('apt-get install -y python-pip python-dev software-properties-common') sudo('apt-get install -y apt-transport-https ca-certificates curl') run('curl -fsSL https://download.docker.com/linux/ubuntu/gpg |' ' sudo ...
44,660
def open_proxy(port=utils.K8S_PORT): """[port] Configures kubernetes proxy to listen on the specified port port: Port to kubernetes proxy to listen to""" # Duplicates the program try: pid = os.fork() except Exception as e: raise e if pid == 0: # This is the child process ...
44,661
def clients_delete(tenant_url, client_name, username=None, password=None, quiet=False): """Deletes an Oauth client PARAMETERS ---------- client_name: string Name of the Oauth client. tenant_url: string URL of the API tenant to interact with. KEYWORD ARGUMENTS...
44,662
def test_process_record_in_progress(lambda_module, ddb_record_in_progress): """ Test process_record() with an in progress record """ response = lambda_module.process_record(ddb_record_in_progress) assert response is None
44,663
def create_list_response_value( *, authorization: types.TAuthorization, uri: types.TUri, auth_info: types.CredentialsAuthInfo, ) -> types.TResponseValue: """ Calculate the response for a list type response. Raises NotFoundError when the uri is not linked to a known spec. Args: ...
44,664
def get_variables(expr): """ Get variables of an expression """ if isinstance(expr, NegBoolView): # this is just a view, return the actual variable return [expr._bv] if isinstance(expr, _NumVarImpl): # a real var, do our thing return [expr] vars_ = [...
44,665
def tousLesIndices(stat): """ Returns the indices of all the elements of the graph """ return stat.node2com.keys() #s=stat.node2com.values() global globAuthorIndex global globTfIdfTab #pprint(globAuthorIndex) #pprint(stat.node2com.values()) #glob node->index return [glo...
44,666
def edit_tx_sheet(request, sheet_id): """Allows the user to edit treatment sheet fields and updates the date of the sheet""" tx_sheet = get_object_or_404(TxSheet, id=sheet_id) form = TxSheetForm(instance=tx_sheet) if request.user == tx_sheet.owner: if request.method == 'POST': for...
44,667
def system( W, L_x, L_sc_up, L_sc_down, z_x, z_y, a, shape, transverse_soi, mu_from_bottom_of_spin_orbit_bands, k_x_in_sc, wraparound, infinite, sc_leads=False, no_phs=False, rough_edge=None, phs_breaking_potential=False): """Create zigzag system Parameters ---------- W ...
44,668
def setup_db(app): """Function used to build a database""" db.app = app db.create_all()
44,669
def list_files(root_dir, mindepth = 1, maxdepth = float('inf'), filter_ext=[], return_relative_path=False): """ Usage: d = get_all_files(rootdir, mindepth = 1, maxdepth = 2) This returns a list of all files of a directory, including all files in subdirectories. Full paths are returned. WARNIN...
44,670
def get_state_x1_pure_state_vector() -> np.ndarray: """Returns the pure state vector for :math:`|-\\rangle`. :math:`|-\\rangle := \\frac{1}{\\sqrt{2}} (|0\\rangle - |1\\rangle)` Returns ------- np.ndarray the pure state vector. """ vec = (1 / np.sqrt(2)) * np.array([1, -1], dtype=n...
44,671
def user_create(user_data): """ Cria um usuário no banco de dados e retorna o objeto criado """ user_model = get_user_model() user = user_model.objects.create_user(**user_data) return user
44,672
def tg_integration_pass( states: typing.List[trajectory_state] ): """ Integrate timesteps :param states: :return: """ for i in range(1, len(states)): states[i].t += states[i - 1].t first = states[0] first.dv = 0 first.dw = 0 first.ddv = 0 first.ddw = 0 l...
44,673
def shannon_entropy(text: str) -> float: """ same definition as in feature processor for feature extraction calculates shannon entropy of a given string """ content_char_counts = Counter([ch for ch in text]) total_string_size = len(text) entropy: float = 0 for ratio in [char_count / tota...
44,674
def cli_test(): """Run the unit tests.""" tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner(verbosity=2).run(tests)
44,675
def solve(inputmatrix): """ This function contains a solution to the data in 4be741c5.json posed by the Abstraction and Reasoning Corpus (ARC). The problem presents an n x m grid, with some rows containing 0-m coloured squares with repetition over a row or colomuns. The solution req...
44,676
def compute_rewards(s1, s2): """ input: s1 - state before action s2 - state after action rewards based on proximity to each goal """ r = [] for g in TASKS: dist1 = np.linalg.norm(s1 - g) dist2 = np.linalg.norm(s2 - g) reward = dist1 - dist2 r.append(rew...
44,677
def decode(i_dunno): """ Decode an I-DUNNO representation into an ipaddress.IPv6Address or an ipaddress.IPv4Address object. A ValueError is raised if decoding fails due to invalid notation or resulting IP address is invalid. The output of this function SHOULD NOT be presented to humans, as recommended ...
44,678
def test_proportions(): """Verify that the proportions of grains in a recipe are properly calculated.""" recipe = RecipeStub() base = base_grain(recipe, 12) caramel = caramel_grain(recipe, 4) recipe.fermentables = [base, caramel] assert isinstance(base.proportion, PercentType) asser...
44,679
async def test_init_failure(circuit): """Test failed init.""" logger = TimeLogger('logger', mstop=True) out = edzed.ValuePoll( 'out', func=lambda: edzed.UNDEF, # func never delivers interval=10, # don't care init_timeout=0.04) # no initdef with p...
44,680
def softmax_loss_naive(W, X, y, reg): """ Softmax loss function, naive implementation (with loops) Inputs have dimension D, there are C classes, and we operate on minibatches of N examples. Inputs: - W: A numpy array of shape (D, C) containing weights. - X: A numpy array of shape (N, D) containing a minib...
44,681
def location_descriptors(): """Provide possible templated_sequence input.""" return [ { "id": "NC_000001.11:15455", "type": "LocationDescriptor", "location": { "sequence_id": "ncbi:NC_000001.11", "interval": { "start...
44,682
def test_report_linux_system_error(iopipe, mock_context, assert_valid_schema): """Asserts that fields collected by the system module are present in a error report""" report = Report(iopipe, mock_context) try: raise Exception("Uh oh, this happened") except Exception as e: report.prepare(...
44,683
def positional_features_gamma(positions: tf.Tensor, feature_size: int, seq_length: Optional[int] = None, bin_size: Optional[int] = None, stddev=None, start_mean=None): ...
44,684
def update_state_machine(stateMachineArn=None, definition=None, roleArn=None, loggingConfiguration=None): """ Updates an existing state machine by modifying its definition , roleArn , or loggingConfiguration . Running executions will continue to use the previous definition and roleArn . You must include at leas...
44,685
def _get_frame_data(mapAPI: MapAPI, frame: np.ndarray, agents_frame: np.ndarray, tls_frame: np.ndarray) -> FrameVisualization: """Get visualisation objects for the current frame. :param mapAPI: mapAPI object (used for lanes, crosswalks etc..) :param frame: the current frame (used for eg...
44,686
def dump(path, load_extension): """Output a SQL dump of the schema and full contents of the database Example: \b sqlite-utils dump chickens.db """ db = sqlite_utils.Database(path) _load_extensions(db, load_extension) for line in db.conn.iterdump(): click.echo(line)
44,687
def calculate_gc(x): """Calculates the GC content of DNA sequence x. x: a string composed only of A's, T's, G's, and C's.""" x = x.upper() return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T'))
44,688
def listdir(path): """ Lists content of a folder. :param str path: Folder to get list from :returns: Directory content list :rtype: tuple example:: dirs, files = xbmcvfs.listdir(path) """ dirs = [] files = [] path = safe_path(path) for item_name in os.listdir(path)...
44,689
def no_float_zeros(v): """ if a float that is equiv to integer - return int instead """ if v % 1 == 0: return int(v) else: return v
44,690
def test_circuit_to_ordering(): """Tests the circuit-to-ordering conversion. This is mostly a change-detecting test, as the heuristic is known to be non-optimal. If this test fails, verify that the new output is an improvement over the old output (either in time or memory cost) and update the test. """ ...
44,691
def clean_up(): """ Try to clean up after a test failure. :return: None """ StratisDbus.destroy_all() assert StratisDbus.pool_list() == []
44,692
def quat_mult(q_1, q_2): """Multiplication in the space of quaternions.""" a_1, b_1, c_1, d_1 = q_1[:, 0], q_1[:, 1], q_1[:, 2], q_1[:, 3] a_2, b_2, c_2, d_2 = q_2[:, 0], q_2[:, 1], q_2[:, 2], q_2[:, 3] q_1_q_2 = torch.stack( ( a_1 * a_2 - b_1 * b_2 - c_1 * c_2 - d_1 * d_2, ...
44,693
def fastqc_trim(out_dir, file1, trim_minlen, threads, adapter_file, file2=False): """Quality and adaptor trimming of fastq files. Takes fastq data (either single or paired), trims sequences using trimmomatic (in the case of paried end reads, it deletes extra files) and uses fastqc to show the user what...
44,694
def handle_speak(event): """ Forward speak message to message bus. """ context = {'client_name': 'neon_speech', 'source': 'audio', 'destination': ["skills"]} bus.emit(Message('speak', event, context))
44,695
def _flip_dict_keys_and_values(d): """Switches the keys and values of a dictionary. The input dicitonary is not modified. Output: dict """ output = {} for key, value in d.items(): output[value] = key return output
44,696
def set_dative_bonds( mol: Chem.rdchem.Mol, from_atoms: Tuple[int, int] = (7, 8) ) -> Optional[Chem.rdchem.Mol]: """Replaces some single bonds between metals and atoms with atomic numbers in fromAtoms with dative bonds. The replacement is only done if the atom has "too many" bonds. Arguments: m...
44,697
def _b2s(b: Optional[bool]) -> Optional[str]: """转换布尔值为字符串。""" return b if b is None else str(b).lower()
44,698
def color_csq(all_csq: Set[str], mane_csq: Set[str]) -> str: """ takes the collection of all consequences, and MANE csqs if a CSQ occurs on MANE, write in bold, if non-MANE, write in red return the concatenated string NOTE: I really hate how I've implemented this :param all_csq: :param ...
44,699