content
stringlengths
22
815k
id
int64
0
4.91M
def water_budget(ds, dim='p'): """Compute water budget if Q2NN is present""" q2_int = (ds.Q2NN * ds.layer_mass).sum(dim) * 86400 q2_ib = q2_int prec = ds.Prec evap = lhf_to_evap(ds.LHF) return xr.Dataset( dict(Prec=prec, evap=evap, Q2=q2_ib, imbalance=q2_ib - (evap - prec)))
5,286,300
def atSendCmdGetOptionInfo(market, code): """ 获取期权信息 :param market: str 市场类型 :param code: str 标的代码 :return: Dotdict 期权信息 :: TODO 期权接口 ... """ func_name = 'atSendCmdGetOptionInfo' atserial.ATraderGetOptionInfo_send(market, code) res = recv_serial(func_name) return re...
5,286,301
def get_split_discordants(data, work_dir): """Retrieve full, split and discordant reads, potentially calculating with samblaster as needed. """ dedup_bam, sr_bam, disc_bam = _find_existing_inputs(data["align_bam"]) if not dedup_bam: dedup_bam, sr_bam, disc_bam = _extract_split_and_discordants(da...
5,286,302
def fuzzy_or(args): """ Or in fuzzy logic. Returns True (any True), False (all False), or None See the docstrings of fuzzy_and and fuzzy_not for more info. fuzzy_or is related to the two by the standard De Morgan's law. >>> from sympy.core.logic import fuzzy_or >>> fuzzy_or([True, False]) ...
5,286,303
def data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete(uuid, cost_name): # noqa: E501 """data_context_path_computation_context_path_comp_serviceuuid_routing_constraint_cost_characteristiccost_name_delete removes tapi.topology.CostCharacteristic #...
5,286,304
def save_integrator(key_name): """ save the integrator if its explicit Parameters --------- key_name """ RK=loadRKM(key_name) if(RK.is_explicit()): print("Saving "+RK.name+" to file "+str(key_name)+".npz" + " and file "+str(key_name)+".mat") # an integrator tablaeu ex...
5,286,305
def get_variables_path(export_dir): """Return the variables path, used as the prefix for checkpoint files.""" return file_io.join( compat.as_text(get_variables_dir(export_dir)), compat.as_text(constants.VARIABLES_FILENAME))
5,286,306
def test_import_distance_law(): """Test importing distance law table files""" xs = hcdl.logbins_xs(fragments, [60000, 20000]) assert np.all(np.isclose(test_xs[0], xs[0], rtol=0.0001)) assert np.all(np.isclose(test_xs[1], xs[1], rtol=0.0001)) assert len(test_ps) == 2 and len(labels) == 2 and len(test...
5,286,307
def print_sudoku(board): """ Prints the game board :param: board: 2d list of ints :return: None """ for i in range(len(board)): if i % 3 == 0 and i != 0: print("- - - - - - - - -") for j in range(len(board[0])): if j % 3 == 0: print(" | ",...
5,286,308
def exit_handler(sig, frame): """ stops execution of the program. """ done_event.set() progress.console.print('[bold red]Stopping Download[/]...') progress.console.print('[red]Download Stopped[/]!') progress.console.print('') sys.exit(0)
5,286,309
def parse_single_geo_arg(key: str) -> GeoPair: """ parses a single geo pair with only one value """ r = _parse_single_arg(key) return GeoPair(r[0], [r[1]])
5,286,310
def check_currency(response: str) -> dict: """Check whether the results have currency conversion Args: response: Search query Result Returns: dict: Consists of currency names and values """ soup = BeautifulSoup(response, 'html.parser') currency_link = soup.find('a', {'href': '...
5,286,311
async def test_state(hass, mock_requester_bus): """Return the contents of _state.""" await assert_setup_sensor(hass, TEST_BUS_CONFIG) state = hass.states.get("sensor.test_name") assert state.state == BUS_RESULT_STATE
5,286,312
def check_serve(options, dbdescr): """Check that all jobs marked as running in the db are marked as running in some cluster jobs scheduler. print jobs that could have crashed/been killed ... Example usage: jobman check <tablepath> """ db = open_db(dbdescr, serial=True) try: ...
5,286,313
def calculate_mean_anniversary(days_of_interest: list): """The function calculate_mean_anniversary calculates the mean anniversary based on a geometric approach. The mean anniversary is valid for the current year. The list of dates are given as string in the format yyyy-mm-dd. """ # Get current ye...
5,286,314
def fix_models_py(models_py): """ The output of inspectdb is pretty messy, so here we trim down some of the mess, add mandatory ID field and fix the bad conversion to CharField (we use TextField instead). """ lines = models_py.split("\n") fixed_lines = [] for line in lines: # Pos...
5,286,315
def _can_extract_intrinsics_to_top_level_lambda(comp, uri): """Tests if the intrinsic for the given `uri` can be extracted. Args: comp: The `tff.framework.Lambda` to test. The names of lambda parameters and block variables in `comp` must be unique. uri: A Python `list` of URI of intrinsics. Return...
5,286,316
def primitiveValueFrom(interp, s_frame, w_cls, w_obj): """ Creates a value of a given Smalltalk object by copying. :param interp: The interpreter proxy. :param s_frame: The stack frame. :param w_cls: The imutable objects target class. :param w_obj: The Smalltalk object to produce an immutable c...
5,286,317
def entertainment(): """ show entertainment posts """ entertainment = Post.query.filter_by(category="Entertainment").all() return render_template('entertainment.html', post=entertainment)
5,286,318
def _GetDesiredVsToolchainHashes(version): """Load a list of SHA1s corresponding to the toolchains that we want installed to build with.""" if version == '2015': # Update 3 final with 10.0.15063.468 SDK and no vctip.exe. return ['f53e4598951162bad6330f7a167486c7ae5db1e5'] if version == '2017': # VS ...
5,286,319
def allsum(my_a, axis=None, dtype=None, out=None, comm=MPI.COMM_WORLD): """ Parallel (collective) version of numpy.sum """ my_sum = np.sum(my_a, axis, dtype) if my_sum is np.ndarray: sum = np.empty_like(my_sum) comm.Allreduce( (my_sum, typemap[my_sum.dtype]), (sum, typemap[sum.dtype])) ...
5,286,320
def sum_of_years_digits(year): """Calculate the sum of years' digits. Arguments: year (``int``): The year to calculate up to. Returns: int: The sum of years' digits. """ if year <= 0: return 0 return year + sum_of_years_digits(year-1)
5,286,321
def resolve_ref(repo_url, ref): """ Return resolved commit hash for branch / tag. Return ref unmodified if branch / tag isn't found Notes ----- Author: Yuvi Panda Copied from https://github.com/yuvipanda/repo2charliecloud/blob/ 44a508b632e801d3b1f0dd1360e38f73d80efc74/repo2c...
5,286,322
def assert_allclose( actual: numpy.ndarray, desired: numpy.ndarray, err_msg: Literal["('tukey', 0.5), 14"], ): """ usage.scipy: 2 """ ...
5,286,323
def codes_code_id_codes_get(code_id, sab=None): # noqa: E501 """Returns a list of {Concept, Code, Sab} associated with the code_id optionally restricted to SAB # noqa: E501 :param code_id: The code identifier :type code_id: str :param sab: One or more SABs to search :type sab: List[str] ...
5,286,324
def generate_c_header (in_c_file, out_h_file, additional_args= []): """ generate the header file for a given c file produced by p4a using cproto. in_c_file : The c file to be processed by cproto out_h_file : The h file to be produced by cproto additional_ args : The additional arguments to the cpro...
5,286,325
def getAbsoluteResourcePath(relativePath): """ Load relative path, in an environment agnostic way""" import sys import os try: # PyInstaller stores data files in a tmp folder refered to as _MEIPASS basePath = sys._MEIPASS except Exception: # If not running as a PyInstaller c...
5,286,326
def plot_data_with_anomalies(data, anomalies, as_var=False): """ Plot the data and add anomalies as line on the graph :argument data: dataframe (same as above) :argument anomalies: DatetimeIndex of dates (corresponding to anomalies) - dtype=datetime64[ns] """ fig, ax = plt.subplots(1, 1, figsize=(2...
5,286,327
def density_supercooled_water(T): """D. E. Hare and C. M. Sorensen: Density of supercooled water 1987 JChemPhys valid between -33.4 to -5/+10 Args: T: in [K] """ a = [0.99986, 6.690e-5, -8.486e-6, 1.518e-7, -6.9484e-9, -3.6449e-10, -7.497e-12] t = T-T0 rho = a...
5,286,328
def repel_from_near(lerp_point, drone_num, course, radius=1.0): """ Отталкиваемся от дронов если они возши в заданный радиус :param name: :param list: :return: """ repel = [0.0, 0.0, 0.0] for i in range(len(drone_offset_list)): if drone_offset_list[i][0] != drone_offset_list[dro...
5,286,329
def get_values(): """ Retrieves two values to multiply """ user_values = input("On the next line, enter the values to multiply,\ separated by commas. \n>> ") input_list = user_values.split(",") final_list = [] #We've split the user's input into a list, but have no idea if it's any good. ...
5,286,330
def spikes(templates, min_amplitude, max_amplitude, n_per_template, spatial_sig, temporal_sig, make_from_templates=True, make_spatially_misaligned=True, make_temporally_misaligned=True, make_collided=True, make_noise=True, return_metadata=True...
5,286,331
def merge_close_peaks(peaks, minimum_distance): """Merge peaks that are too close to each-other vertically. Peaks that fall within the dilation mask are spurious and likely not peaks we want. When two peaks fall below the minimum distance, the smallest one will be discarded. Parameters: ----------...
5,286,332
def test_decrypt() -> None: """Test the decrypt() method against a set of precomputed keys.""" for clear, encrypted in PRECOMPUTED: assert decrypt(bytes.fromhex(encrypted), KEY) == clear
5,286,333
def LruCache(maxsize=None): """LRU Cache decorator. Args: maxsize: the maximum cache size, or None for unlimited size. """ def wrapper(fn): return functools32.lru_cache(maxsize=maxsize)(fn) return wrapper
5,286,334
def inspire_search(search=""): """Searches Inspire.""" import time import shutil import os import json import base64 # Path for the temporary bibtex results. tempf = os.path.join(alp.cache(),"results.bib") # Path for the temporary latest parsed results. lastf = os.path.join(alp...
5,286,335
def delete_files(base_dir, f_filter): """Function: delete_files Description: Delete test files in base directory with passed file filter. Arguments: (input) base_dir -> Base directory path to testing directory. (input) f_filter -> File filter for searching. """ for item in glo...
5,286,336
def parse_inputs(): """ Parser function to take care of the inputs """ parser = ArgumentParser(description='Argument: python data_preprocess.py <data_direction> <output_annotation_path> <test_ratio>') parser.add_argument('data_dir', type=str, help='Enter path to data direction.') ...
5,286,337
def plot_pastis_matrix(pastis_matrix, wvln=None, out_dir='', fname_suffix='', save=False): """ Plot a PASTIS matrix. :param pastis_matrix: array, PASTIS matrix in units of contrast/nm**2 :param wvln: float, optional, wavelength at which the PASTIS matrix was generated in nm. If provided, converts ...
5,286,338
def test_map_internal_to_remote_ports(hass, mock_miniupnpc): """Test mapping local to remote ports.""" ports = OrderedDict() ports['hass'] = 1000 ports[1883] = 3883 result = yield from async_setup_component(hass, 'upnp', { 'upnp': { 'local_ip': '192.168.0.10', 'ports...
5,286,339
def concretise_config( config: StrConfig, available_domains: List[Domain] ) -> ObjConfig: """Dereference configuration.""" domain = find_by_repr(available_domains, config.domain) categories = list(gather_categories(domain.tools).keys()) loaders = [find_by_repr(domain.tools + categories, c) for c in ...
5,286,340
def nextDay(year, month, day): """计算指定日期的下一天(假设给定的日期合法)""" if day < daysInMonth(year, month): return year, month, day + 1 else: if month == 12: return year + 1, 1, 1 else: return year, month + 1, 1
5,286,341
def runTestCasesWithInput(test_cases, test_input, yaml_reporter, oonib_reporter=None): """ Runs in parallel all the test methods that are inside of the specified test case. Reporting happens every time a Test Method has concluded running. Once all the test methods have been called we check to se...
5,286,342
def encode_cli(file_path: str, **kwargs): """Encode + compress a dataset""" TokenDataset(file_path, save_cache=True, **kwargs)
5,286,343
def load_david_worksheet(fname='fMRI MA significance bias database 03-24-13.xlsx', verbose=False): """load the David et al. data from excel workbook and return ID and sample size""" workbook = xlrd.open_workbook(fname) sheet=workbook.sheet_by_name('Original Sheet') studies={} all_ids=[] ...
5,286,344
def file_lines(dictionary_file): """ Counts the number of lines of the given file. Parameters ------- dictionary_file: file The text file Returns ------- int The number of lines of the given file """ buf = mmap(dictionary_file.fileno(), 0) lines = 0 read...
5,286,345
def is_holiday(date): """ check if one date is holiday in China. in other words, Chinese people get rest at that day. :type date: datetime.date | datetime.datetime :rtype: bool """ return not is_workday(date)
5,286,346
def read_dataset_and_unit_h5(h5, expected_unit=None, convert=True): """ Reads a dataset that has openPMD unit attributes. expected_unit can be a pmd_unit object, or a known unit str. Examples: 'kg', 'J', 'eV' If expected_unit is given, will check that the units are compatible. If conv...
5,286,347
def make_sparse_convmodule(in_channels, out_channels, kernel_size, indice_key, stride=1, padding=0, conv_type='SubMConv3d', norm_cf...
5,286,348
def autoCheck2Remind(): """ 自动检测是否有日记应该推送提醒 """ timeStamp = time.time() timeStamp -= int(timeStamp) % 60 # 减去秒数 timeNow = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp)) time5minLater = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp + 5 * 60 - 1)) # 应减一,否则整点(5min...
5,286,349
def get_zcoeffs(csv, imfreq): """ Given the input frequency of the image, returns the Pandas dataframe with the coefficients corresponding to the input frequency. The frequencies in the input CSV file are expected to be in MHz. Inputs: csv Input CSV filename, string imfreq Imag...
5,286,350
def test_func(s, sr, maximum_duration=30, minimum_duration=None, frame_length=256, nb_mixtures=3, threshold=0.3, return_vad=False, return_voices=False, return_cut=False): """ Splitting an audio based on VAD indicator. * The audio is segmented into multiple with length given by `frame...
5,286,351
def test_cli_configuration(cli_runner): """Call the version command with a configuration file.""" result = cli_runner.invoke( cli, ["--version", "--config", "../src/dhm_module_base/confis/dummy.ini"], catch_exceptions=False, ) assert result.exit_code == 0
5,286,352
def _find_layer(model: torch.nn.Module, target_layer: Union[str, torch.nn.Module]) -> torch.nn.Module: """Find the specified layer in a model. Args: model: a neural network model as a PyTorch Module. target_layer: the target layer in the model. If a str, will be used as the name...
5,286,353
def article(topic: str, article_date: str, title_slug: str) -> tuple: """ **article** :param topic: :param article_date: :param title_slug :return: """ link_slug: str = f'{topic}/{article_date}/{title_slug}' article_data: Optional[dict] = Articles.get_article_by_link(link_slug=...
5,286,354
def parse_simple_expression_list(l): """ This parses a comma-separated list of simple_expressions, and returns a list of strings. It requires at least one simple_expression be present. """ rv = [ l.require(l.simple_expression) ] while True: if not l.match(','): break ...
5,286,355
def collect_ibkr_listings(exchanges=None, sec_types=None, currencies=None, symbols=None, universes=None, sids=None): """ Collect securities listings from Interactive Brokers and store in securities master database. Specify an exchange (optionally filtering by security type, cu...
5,286,356
def largest_indices(x, K): """Returns the indices of K largest entries in x by magnitude Args: x (jax.numpy.ndarray): An data vector/point K (int): The number of largest entries to be identified in x Returns: (jax.numpy.ndarray): An index vector of size K identifying the K largest ...
5,286,357
def flatten(val: Iterable[Iterable[Any]]) -> List[Any]: """ Flatens a list of list into a list >>> flatten( [['abc','def'],[12,34,46],[3.14, 2.22]]) ['abc', 'def', 12, 34, 46, 3.14, 2.22] """ return list(itertools.chain(*val))
5,286,358
def surprisal_graph(transition_matrix, states=None, symmetrized=True, stationary_distribution=None): """Return the surprisal graph of a discrete-time Markov chain. Parameters ---------- transition_matrix : (N, N) array_like Transition matrix of a discrete-time Markov chain. Must be a s...
5,286,359
def get_output_list(file_row): """Return list of dict for output file""" data = [] list_mammo = get_row_nr(file_row, 'mammo_params') list_us = get_row_nr(file_row, 'us_params') list_mri = get_row_nr(file_row, 'mri_params') all_params = list_mammo + list_us + list_mri for x in range(len(all_p...
5,286,360
def update_parameters(updates): """ Takes a list of strings and values for updating parameters in the parameter dictionary Example: updates = [(key, val), (key, val)] """ for (key, val) in updates.items(): par[key] = val print('Updating:', key, '-->', val) update_dependen...
5,286,361
def to_csv(members): """Convert JSON data structure to CSV string.""" with io.StringIO() as fp: cw = csv.writer(fp) if len(members): cw.writerow(members[0].keys()) for member in members: cw.writerow(member.values()) value = fp.getvalue() return value
5,286,362
def plot_location(latitude, longitude, bearing, distance): """Plot a new location based on starting point, bearing and distance""" bearing_rad = math.radians(bearing) lat1 = math.radians(latitude) lon1 = math.radians(longitude) d_over_r = distance / EARTH_RADIUS lat2 = math.asin( math...
5,286,363
def get_text_from_html(x): """ """ output = '' try: ps = subprocess.Popen(('echo', x), stdout=subprocess.PIPE) output = subprocess.check_output(('lynx', '--dump', '--stdin'), stdin=ps.stdout) ps.wait() except: pass import ipdb ipdb.set_trace() return ou...
5,286,364
def num_sources(): """Get the number of sources.""" return len({s for s in SourceName})
5,286,365
def _get_panelargs( side, share=None, width=None, space=None, filled=False, figure=False ): """ Return default properties for new axes and figure panels. """ if side not in ('left', 'right', 'bottom', 'top'): raise ValueError(f'Invalid panel location {side!r}.') space = space_user = ...
5,286,366
def relu(x): """ REctified Linear Unit: y = x if x >= 0; y = 0 if x < 0; :param owl.NArray x: input :return: result ndarray :rtype: owl.NArray """ return _owl.NArray.relu(x)
5,286,367
def find_max_treatment_effect_phenotype(g, zeta_probs, factual_outcomes): """ Find the group with the maximum treatement effect phenotype """ mean_differential_survival = np.zeros(zeta_probs.shape[1]) # Area under treatment phenotype group outcomes_train, interventions_train = factual_outcomes ...
5,286,368
def make_random_image(filename=None, dims=(10, 10, 10), xform=None, imgtype=1, pixdims=None, dtype=np.float32): """Convenience function which makes an image containing random data. Saves and returns the...
5,286,369
def literal_eval(str_list: str, no_string_quotation: bool = False): """ the list parser will convert list in string to the list and there is an option available `no_string_quotation` if you string contains the needed quotations like bellow: Example = "['hello', 5, 7, ('damage', 5)]" make it ...
5,286,370
def _check_lat_or_long(val: Any, clean: bool, hor_dir: str) -> Any: """ Function to check if a coordinate instance is valid """ # pylint: disable=too-many-boolean-expressions if val in NULL_VALUES: return (None,) * 4 + (0,) if clean else False pat = LAT_PATTERN if hor_dir == "lat" else ...
5,286,371
def integrate(avg_daily_sentiment, interval): """ Takes a list of average daily sentiment scores and returns a list of definite integral estimations calculated with Simpson's method. Each integral interval is determined by the `interval` variable. Shows accumulated sentiment. """ # Split into sliding window list ...
5,286,372
def assert_equal(actual: Literal["robust_approx"], desired: Literal["robust_approx"]): """ usage.statsmodels: 1 """ ...
5,286,373
def split_sentences(inp_text, nlp_model): """ Splits an input string into sentence determined by spacy model :param inp_text: string with input text :param nlp_model: sciSpacy model :return: list of sentences in string format """ doc = nlp_model(inp_text) sentences_list = [sentence.text ...
5,286,374
def _get_rotation_indices_gl(self, linkages): """ Precompute indices that are then used to rotate along the i-j axis only the proper portion of the coordinates array. Works only for glycans. Returns rotation_indices : dict of dict of tuples dictionary of residue numbers, dicctiona...
5,286,375
def test_conditional_bad_transition(): """ Test transition between blocks with a random string """ cond = Conditional.directive(None) cond.open("if", random_str(5, 10)) for transition in ( ["if", "endif"] + [random_str(1, 10, ["elif", "else"]) for _x in range(10)] ): with pyt...
5,286,376
def create_pb_states(): """Create PB states in the config DB. This creates the PB states with status = RUNNING, and for any workflow matching the list of receive workflows, it adds the receive addresses. """ for txn in CONFIG_DB_CLIENT.txn(): pb_list = txn.list_processing_blocks() ...
5,286,377
def date_from_str(text: str) -> Sequence[str]: """Get the date tuple (year, month) from the text string.""" logger = logging.getLogger('date_from_str') # No leading digit, then 1 or 2 followed by 3 digits (for years 1ddd and # 2ddd), then any of -:\/ then 2 digits, then any of -:\/ then optional 2 ...
5,286,378
def get_nodes_for(node_types: Dict[NodeType, NodeTypeConfigDict], existing_nodes: Dict[NodeType, int], head_node_type: NodeType, max_to_add: int, resources: List[ResourceDict], strict_spread: bool = False) -> Dict[NodeType, int]: ...
5,286,379
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up WLED light based on a config entry.""" wled: WLED = hass.data[DOMAIN][entry.entry_id][DATA_WLED_CLIENT] # Does the WLED device support RGBW ...
5,286,380
def _point(x,index=0): """Convert tuple to a dxf point""" return '\n'.join([' %s\n%s'%((i+1)*10+index,float(x[i])) for i in range(len(x))])
5,286,381
def train_epoch( model, auxiliarynet, criterion, train_loader, device, epoch, optimizer, logger, ): """Train one epoch.""" model.train() auxiliarynet.train() batch_time = AverageMeter("batch_time") data_time = AverageMeter("data_time") losses = AverageMeter("loss...
5,286,382
def masternode_commands(): """ Provide commands for working with masternode. """ pass
5,286,383
def test_close_a_file(editorstack, outlineexplorer, test_files): """ Test that the content of the outline explorer is updated corrrectly after a file has been closed in the editorstack. Regression test for spyder-ide/spyder#7798. """ editorstack = editorstack(test_files) treewidget = outlin...
5,286,384
def print_menu(): """Function to print the menu to operate the Address Book. """ os.system('clear') print '-----------------' print 'Address book menu' print '-----------------' print '1.List' print '2.Add' print '3.Delete' print '4.Modify' print '0.Exit'
5,286,385
def myip() -> str: """returns a string with the computers default IP address """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip
5,286,386
def edit(token, action_type): """ Edit the labeling of the project and update the project in the database. """ start = timeit.default_timer() # obtain 'info' parameter data sent by .js script info = {k: json.loads(v) for k, v in request.values.to_dict().items()} # TODO: remove frame fro...
5,286,387
def not_empty(message=None) -> Filter_T: """ 验证输入不为空。 返回: nonebot.typing.Filter_T: """ def validate(value): if value is None: _raise_failure(message) if hasattr(value, '__len__') and value.__len__() == 0: _raise_failure(message) return va...
5,286,388
def eval_func(scoring_result: Input, eval_output: Output = None): """eval component""" print("hello evaluation world...") lines = [ f"Scoring result path: {scoring_result}", f"Evaluation output path: {eval_output}", ] for line in lines: print(line) # Evaluate the incom...
5,286,389
def get_video_dimensions(lines): """Has it's own function to be easier to test.""" def get_width_height(video_type, line): dim_col = line.split(", ")[3] if video_type != "h264": dim_col = dim_col.split(" ")[0] return map(int, dim_col.split("x")) width, height = None, No...
5,286,390
def factorial(x): """ The factorial_ (denoted :math:`n!`) is the product of all positive integers less than or equal to a positive integer (:math:`n`). .. _factorial: https://en.wikipedia.org/wiki/Factorial Equation: .. math:: n! = \\prod_{k=1}^n k Args: x: A numer...
5,286,391
def __get_database_filepath(config: ChiaTeaConfig) -> str: """Get the database filepath from the config Parameters --------- config : ChiaTeaConfig config to read filepath for cert and key Returns ------- db_filepath : str path where the database is or will be stored ""...
5,286,392
def main(): """mian fun""" makearr() solvearr()
5,286,393
def brownian_bridge(n_step, sample_shape=()) -> torch.Tensor: """ :param n_step: first and last steps are 0 and 1 :param sample_shape: :return: b[step, sample_shape] """ assert n_step >= 2 if not isinstance(sample_shape, Iterable): sample_shape = (sample_shape,) to_squeeze =...
5,286,394
def walk_timeline(ses, user_id, tweet_id=None, filter_user=True, max_pages=30): """ traverse timeline of specific user """ url = "https://api.twitter.com/1.1/statuses/user_timeline.json" params = {"user_id": user_id, "include_rts": "true", "count": 200} if tweet_id: params["since...
5,286,395
def expand_ambiguous_dna(seq): """return list of all possible sequences given an ambiguous DNA input""" d = IUPAC.IUPACData.ambiguous_dna_values return tuple(map("".join, product(*map(d.get, seq))))
5,286,396
def _check_selection(selection): """Handle default and validation of selection""" available = ["counts", "exposure", "background"] if selection is None: selection = available if not isinstance(selection, list): raise TypeError("Selection must be a list of str") for name in selecti...
5,286,397
def read_wgs(filename, wgsname=None, boun_cond=None): """ read a LaWGS file and create a LaWGS object :param filename: filename of the LaWGS file :param wgsname: "name" for the LaWGS object :param boun_cond: a tuple containing the boundary conditions of each network :return: LaWGS object "...
5,286,398
def calculate_v6_Psi2(chi_6222, chi_6222_err, vn_array): """ v6(Psi2) = chi_6222*sqrt(<abs(V2)**6>) """ dN = real(vn_array[:, 0]) Q2 = dN*vn_array[:, 2] Q4 = dN*vn_array[:, 4] Q6 = dN*vn_array[:, 6] nev = len(dN) N6_weight = dN*(dN - 1.)*(dN - 2.)*(dN - 3.)*(dN - 4.)*(dN - 5.) ...
5,286,399