content
stringlengths
22
815k
id
int64
0
4.91M
def obtain_safety_stock_vector(theta: np.ndarray, load_ph: np.ndarray, sigma_2_ph: np.ndarray, state: np.ndarray, debug_info: bool = False): """ Returns vector whose components are the saf...
5,293,900
def get_method_from_html(html_file): """ Parse simulation method name from html_file """ input_file = open(html_file, 'r') for line in input_file: if line.find("Simulation Method") > 0: line = next(input_file) break token = line[4:].split("<")[0] input_file.cl...
5,293,901
def make_test_problems(settings): """Creates test problems from settings. Args: settings (list[dict]): raw settings of the problems Returns: list[ExtensionTestProblem] """ problem_dicts = [] for setting in settings: setting = add_missing_defaults(setting) devic...
5,293,902
def test_dataset_to_file_derived_var(mock_get_input_files, mock_data_availability, config_user): """Test ``_dataset_to_file`` with derived variable.""" mock_get_input_files.side_effect = [ ([], [], []), ([sentinel.out_file], [sentinel.dirname], [sentinel.file...
5,293,903
def plot_hits( ax, hits_dict, reference_length=None, plot_range=None, hide_missing_pairs=True, bar_height=0.8, bar_color="blue", sort_key=lambda i: i, ): """ Groups hits by query, and places above reference hits_dict: map from query_id to list of hit objects bar_color...
5,293,904
def UserUpdate(fCallback): """Get User and log update requests passing to fCallback The log will be handed to fCallback when 'ok' is received""" def log_update_requests_and_call(self, *args, **kwargs): cmd = args[0] arg = args[1] # Empty line if cmd is None: ret...
5,293,905
def get_sub_graph_external_input_output( predict_net: caffe2_pb2.NetDef, sub_graph_op_indices: List[int] ) -> Tuple[List[Tuple[str, int]], List[Tuple[str, int]]]: """ Return the list of external input/output of sub-graph, each element is tuple of the name and corresponding version in predict_net. e...
5,293,906
def run_xsslint(options): """ Runs xsslint/xss_linter.py on the codebase """ thresholds_option = getattr(options, 'thresholds', '{}') try: violation_thresholds = json.loads(thresholds_option) except ValueError: violation_thresholds = None if isinstance(violation_thresholds, ...
5,293,907
def magmablas_csymmetrize(uplo, n, A, lda): """ Symmetrize a triangular matrix. """ uplo = _uplo_conversion[uplo] status = _libmagma.magmablas_csymmetrize(uplo, n, int(A), lda) magmaCheckStatus(status)
5,293,908
def test_error_on_negative_distance(schema: Type[BaseModel], data: Dict[str, Any]): """ Test that a distance is not under zero """ with pytest.raises(ValidationError) as exc_info: schema(distance=-0.5, **data) assert len(exc_info.value.errors()) == 1 assert exc_info.value.errors()[0]["l...
5,293,909
def _butterworth(ts, low_frequency, high_factor, order, sampling_frequency): """Butterworth filter Parameters ---------- ts: np.array T numpy array, where T is the number of time samples low_frequency: int Low pass frequency (Hz) high_factor: float High pass factor (pro...
5,293,910
def pickle_population(population, parent, save_path, run): """ Save the objects (pickle) necessary to later resume evolution: Pickled objects: .population .parent .random states: numpy and random Useful for later conducting more generations. Replac...
5,293,911
def position_callback(message): """ロボットの現在位置をsubscribeする関数""" global x;global y x = message.pose[-1].position.x y = message.pose[-1].position.y
5,293,912
def mk_conf_file(conf): """ Creates config file in temporary file. """ tmp_fp = tempfile.mktemp() with open(tmp_fp, "w") as f: print(mk_conf_str(conf), file=f) return tmp_fp
5,293,913
def get_string(request, key): """Returns the first value in the request args for a given key.""" if not request.args: return None if type(key) is not bytes: key = key.encode() if key not in request.args: return None val = request.args[key][0] if val is not None and typ...
5,293,914
def smart_get(driver, url, timeout=10): """ 限制访问的时间,避免等待过长的时间! """ try: driver.set_page_load_timeout(timeout) driver.get(url) except Errors.TimeoutException: driver.set_page_load_timeout(timeout / 3)
5,293,915
def char_word_tokenize(text): """分词器、中文单独成词,英文单词、连续数字作为一个词""" # 大写转小写,繁体转简体 text = zhconv.convert(text.lower(), 'zh-cn') # 全角转半角 text = full_to_half(text) tokenized_chs = [] text_len = len(text) i = 0 while i < text_len: ch = text[i] # 中文字符 if ch in all: ...
5,293,916
def anomalyService(dimValObj, dfDict, anomalyDefProps, detectionRuleType, detectionParams): """ Method to conduct the anomaly detection process """ df = pd.DataFrame(dfDict) anomalyId = dimValObj["anomalyId"] dimVal = dimValObj["dimVal"] contriPercent = dimValObj["contriPercent"] output ...
5,293,917
def test_set_use_not_str(): """Tests that unkown object becomes filled in usable""" test_item = types.Item() test_item.set_usable(object) assert test_item.usable == types.NotUsable,\ "Failed to set unknown object use to notusable"
5,293,918
def binarySearch(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if len(nums) == 0: return -1 left, right = 0, len(nums) - 1 while left + 1 < right: mid = (left + right) // 2 if nums[mid] == target: return mid elif n...
5,293,919
def tokenize(text): """ Function that tokenizes an input text string Parameters: text (str): Input text Returns: list (str): List of tokens extracted from the input text """ tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for t...
5,293,920
def threaded_async(func: _typing.Callable): """ Helper decorator used to resolve future in a thread-safe manner. """ future: _typing.Coroutine = func() def _call(): """ Inner function used to resolve the future correctly. """ return _asyncio.run_coroutine_threadsafe(...
5,293,921
def barycenter(P, K, reference="debiased", **kwargs): """Compute OT barycenter.""" ndim = P.ndimension() if ndim > 3 or ndim <= 1: raise ValueError("Data dimension must be 2 for 1d distributions" " or 3 for 2d distributions.") if reference == "debiased": if ndim ...
5,293,922
def _run_interactive_shell(): """Run an interactive shell as if it were the first thing being run. """ builtins = __builtins__ code_ = code import __main__ __main__.__dict__.clear() __main__.__dict__.update(dict( __name__ = "__main__", # normal interactive shell lea...
5,293,923
def map_serial_number(facilities) -> str: """Map serial number.""" facility = facilities.get("body", {}).get("facilitiesList", [])[0] return str(facility.get("serialNumber", None))
5,293,924
def get_shape_xyz(self): """Return the mode shape in cartesian coordinates. Parameters ---------- self : Mode a Mode object Returns ------- shape : ndarray ndarray of the shape (Nnodes*Ndof) """ if self.shape_xyz is not None and self.shape_xyz.size != 0: re...
5,293,925
async def reg_full_m(ctx, user: discord.Member, *, name): """[Mods only] Registers someone else with full name explicitly.""" await register_actual(ctx, user, name=name, is_full_name=True)
5,293,926
def product_check(product_name): """ Check if product name already exists in the database """ if mongo.db.products.find_one({"name": product_name}): # Display flash message flash("Product " + product_name + " already exists in the database", "warning") product_check...
5,293,927
def tff_cc_library_with_tf_deps(name, tf_deps = [], **kwargs): """A version of `cc_library` that links against TF statically or dynamically. Args: name: A unique name for this target. tf_deps: List of TensorFlow static dependencies. **kwargs: `cc_test` keyword arguments. """ deps = kw...
5,293,928
def _bootstrap_basic(): """ Perform basic operations on the AMI (e.g. import security keys, configure timezone) """ # https://forums.aws.amazon.com/thread.jspa?messageID=341020 sudo("gpg --keyserver keyserver.ubuntu.com --recv-key 40976EAF437D05B5") sudo("gpg -a --export 40976EAF437D05B5 | apt-key add -") ...
5,293,929
def login(body): """ todoc """ try: username = body["username"] password = body["password"] except: return _get_bad_request() user = User.query.filter(User.username == username).first() if not user: return {"code": "NOT_FOUND", "message": "Wrong username/password"...
5,293,930
def genPlayerActionFiles (sourcePath, processedPath): """Transform four files extracted from the demo file into player action files. Before read the code, I strongly suggest you to read the "CSGO Player Recognition by RNN (LSTM).pdf" in the Doc folder first. This file can give you the overview o...
5,293,931
def indicate_bind_completed(kek_meta_dto, kek_datum): """Updates the supplied kek_datum instance per the contents of the supplied kek_meta_dto instance. This function is typically used once plugins have had a chance to bind kek_meta_dto to their crypto systems. :param kek_meta_dto: :param kek_datum...
5,293,932
def custom_check(data, id_or_name): """Show group custom_check.""" group = data.client.show("custom_check", "config", id_or_name) if not group: return if not group["scripts"]: return columns = ("name", "script") output.list(columns, group["scripts"])
5,293,933
def get_arguments(): """Read arguments for the program and returns the ArgumentParser""" parser = argparse.ArgumentParser(description='''DroidLysis3 is a Python script which processes Android samples. \n 1/ It extracts properties from the samples (e.g connects to Internet, roots the phone...). The extracted p...
5,293,934
def plot_hpiezo_daily(codes, df_obs, df_sim, figure_dir): """ Plot observed and simulated piezometric head evolutions Parameters --------- codes: list df_obs: pd.DataFrame df_sim: pd.DataFrame figure_dir: str """ for code in codes: fig = plt.figure(figsize=(8,6)) ...
5,293,935
def get_atoms_id(atoms: Atoms) -> str: """ Returns a unique ID for the Atoms object. Note: The .info dict and calculator is excluded from the hash generation. Parameters ---------- atoms .Atoms object Returns ------- md5hash MD5 hash of the .Atoms object """ ...
5,293,936
def get_payees(): """Loads the payees override file""" return load_config_file("payees")
5,293,937
async def cmd_raw_gm_system(ctx: commands.Context, *, star_system_id: str = None): """ Get raw star system design data from the PSS API. Usage: /raw gm system <id> <format> Parameters: id: An integer. If specified, the command will only return the raw data for the GM system with the sp...
5,293,938
def test_players_urls_new(): """ Tests an API call to create a new URL for a particular player """ response = players_instance.urls( player_id=player_id, option='new', param_dict = { 'label': 'Test label', 'height': 1080, 'width': 1920, 'bi...
5,293,939
def _get_maxmem(profile_df): """ Get current peak memory :param pandas.core.frame.DataFrame profile_df: a data frame representing the current profile.tsv for a sample :return str: max memory """ return "{} GB".format(str(max(profile_df['mem']) if not profile_df['mem'].empty else 0))
5,293,940
def read(file_ref, **kwargs): """Read a LAS file. Note that only versions 1.2 and 2.0 of the LAS file specification are currently supported. Arguments: file_ref (file-like object, str): either a filename, an open file object, or a string containing the contents of a file. Retu...
5,293,941
def mk_sentence(_id, topic, category, title): """ e.g. [테슬라-모빌리티] 👀 테슬라가 승차공유 서비스 Tesla Network를 출시합니다. https://snak.news/newsList/news/208?channel=slack&corp=pozalabs""" link = SNAK_URL.format(_id=_id, corp=CORP) return f"[{topic}-{category}] {title} {link}"
5,293,942
def get_global_barrier_order(kernel): """Return a :class:`tuple` of the listing the ids of global barrier instructions as they appear in order in the kernel. See also :class:`loopy.instruction.BarrierInstruction`. """ barriers = [] visiting = set() visited = set() unvisited = set(insn....
5,293,943
def str2bool(v): """ Helper to pass boolean arguements. Extracted from: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Author: @Maxim """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif...
5,293,944
def MaskedNLL(target, probs, balance_weights=None): # adapted from https://gist.github.com/jihunchoi/f1434a77df9db1bb337417854b398df1 """ Args: target: A Variable containing a LongTensor of size (batch, ) which contains the index of the true class for each corresponding step....
5,293,945
def test_nclob__str___method_for_nonascii_chars_raises(): """Test that the magic __str__ method raise Unicode error for non-ascii chars""" if not PY2: pytest.skip('test only makes sense in PY2') data = u'朱の子ましけ' nclob = lobs.NClob(data) with pytest.raises(UnicodeEncodeError): str(nc...
5,293,946
def count_triangle(tbl_name, conn): """ input is a matrix """ tol = 0.1 b = 'b' lim = 10 cur = conn.cursor() tn = tbl_name print "create matrix..." create_vector_or_matrix(b, conn) print "Counting dimension..." calc_dim_query = "select max(row), max(col) from %s" % (tn) cur.e...
5,293,947
async def process_headers(headers): """Filter out unwanted headers and return as a dictionary.""" headers = dict(headers) header_keys = ( "user-agent", "referer", "accept-encoding", "accept-language", "x-real-ip", "x-forwarded-for", ) return {k: header...
5,293,948
def test_save_array_view(exopy_qtbot, root_view): """Test SaveView widget. """ task = SaveArrayTask(name='Test') root_view.task.add_child_task(0, task) show_and_close_widget(exopy_qtbot, SaveArrayView(task=task, root=root_view))
5,293,949
def handleReactionTimeStable(): """More stable but not recommended, since it's slower than most humans...""" startScreenPresent = EC.presence_of_element_located( (By.XPATH, "//div[@class='css-42wpoy e19owgy79']")) try: WebDriverWait(driver, 3).until(startScreenPresent).click() exce...
5,293,950
def Bound_EXT(S, Ex, boundaries): """ This function computes the extension of a signal for filtering purposes :param S: The Input signal :param Nf: The Size of the Kernel (must be an odd number!) :param boundaries: The type of extension: ‘reflect’ (d c b a | a b c d | d c b a) The inpu...
5,293,951
def infer_dtype_from_array( arr, pandas_dtype: bool = False ) -> Tuple[DtypeObj, ArrayLike]: """ Infer the dtype from an array. Parameters ---------- arr : array pandas_dtype : bool, default False whether to infer dtype including pandas extension types. If False, array belon...
5,293,952
def np(url): """ Transforms a reddit link into a no participation URL (which in some subreddits hides voting arrows, to help prevent administrator shadowbans. :param url: URL to transform :return: A no participation (NP) link """ url = urlparse(url) return "https://np.reddit.com{}".forma...
5,293,953
def gzip_assets(): """ GZips every file in the media directory and places the new file in the gzip directory with the same filename. """ run('cd %(site_path)s; python gzip_assets.py' % env)
5,293,954
def test_get_onboarding(oauth_client, response): """Retrieve onboarding.""" response.get('https://api.mollie.com/v2/onboarding/me', 'onboarding_me') onboarding = oauth_client.onboarding.get('me') assert isinstance(onboarding, Onboarding) assert onboarding.name == 'Mollie B.V.' assert onboardin...
5,293,955
def sample(method, clf, x0, start, sampling_method, n_samples=[50_000, 100_000], prior=None, inn_prods=None, theta_kern=None): """ Uses a density ratio estimator clf to sample from the posterior for x0 and prior. Inputs: - method: str, either "signature" or "gru-resnet" depending on which classifier is...
5,293,956
def get_authenticate_headers(request, error_type="invalid_token"): # type: (Request, Str) -> Optional[HeadersType] """ Obtains all required headers by 401 responses based on executed :paramref:`request`. :param request: request that was sent to attempt authentication or access which must respond with U...
5,293,957
def central_comp(central, standard_parameters): """ todo docstring """ for i, j in central.iterrows(): if j['electricity_bus'] in ['Yes', 'yes', 1]: create_standard_parameter_bus( label='central_electricity_bus', bus_type="central_electrici...
5,293,958
def get_current_and_head_revision( database_url: str, alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]: """ Returns a tuple of ``(current_revision, head_revision)``; see :func:`get_current_revis...
5,293,959
def extract_root(pitch): """ Try to extract an integer root from a non-integral pitch """ if isinstance(pitch[0], Fraction): pitch = pitch + 0 root = 1 while True: d = 1 for coord in pitch: if coord.denominator > 1: d = ...
5,293,960
def get_kind(cm, kind, value): """ Return the value of the 'kind' argument :param cm: a ClassManager object :type cm: :class:`ClassManager` :param kind: the type of the 'kind' argument :type kind: int :param value: the value of the 'kind' argument :type value: int :rtype: string ""...
5,293,961
def _generate_global_config() -> str: """Generate a standard configuration file for the application in the user's home folder ~/.aiscalator/config/aiscalator.conf from the template file in aiscalator/config/template/aiscalator.conf """ logger = getLogger(__name__) dst = os.path.join(os.path.expa...
5,293,962
def deleteByNum(): """删除temp里的文件""" dirpath="D:/Project/aip-python/temp/" files = os.listdir(dirpath) # 列出目录下的文件 for file in files: os.remove(dirpath+file) # 删除文件 return
5,293,963
def goto(line, column=None): """Sets the cursor to the coordinates (column, line). The default column value is the current column. Warning: The origin is (1, 1), not (0, 0).""" assert column is None or isinstance(column, int) assert isinstance(line, int) assert column is not None and column >= 0 ...
5,293,964
def temp_fetch(url): """Fetch a URL and save it in a temporary file, returning the filename.""" conn = urllib2.urlopen(url) try: fp = tempfile.NamedTemporaryFile(delete=False) LOG.info("Saving %s to a temporary file" % truncate_url(url)) try: fp.write(conn.read()) ...
5,293,965
def load_video_infos_csv(file_path: str): """load the values of a .csv file containing the info of all videos in the directory Args: file_path (str): the file path to the file debug_function (bool, optional): Defaults to None. Returns: (list(dict)): the values from .csv fi...
5,293,966
def offset_xlabel(label, axes, offset): """ Draws an xlabel that is at the given offset from the bottom of the axis, regardless of the status of the tick labels. (Normal xlabels adjust upwards if tick labels are removed) """ text = matplotlib.text.Text(.5, 0, label, horizontalalignment='center')...
5,293,967
def mean_abs_mismatch(slice0, slice1): """ Mean absoute difference between images """ return np.mean(np.abs(slice0 - slice1))
5,293,968
def loads(payload, **kwargs): """ Deserialize an object from a bytestring. :param bytes payload: the bytestring to serialize :param kwargs: keyword arguments passed to :class:`~.CBORDecoder` :return: the deserialized object """ fp = uio.BytesIO(payload) return CBORDecoder(fp, **kwargs).d...
5,293,969
def encode_with_sp_as_pieces(in_file, out_file, model_file): """ Encode raw text into sentence pieces. """ spp = sentencepiece.SentencePieceProcessor() spp.load(model_file) for line in in_file: pieces = spp.encode_as_pieces(line.rstrip()) line_pieces = ' '.join(pieces) + '\n' ...
5,293,970
def test_01(): """runs hello""" rv, out = getstatusoutput('{}'.format(prg)) assert rv == 0 assert out.rstrip() == 'Hello, World.'
5,293,971
def test_query_trade_history(function_scope_coinbasepro): """Test that querying trade data from coinbase pro works""" cb = function_scope_coinbasepro cb_query_mock, get_mock = create_coinbasepro_query_mock( cb, original_get=requests.get, ) with cb_query_mock, get_mock: trades...
5,293,972
def test_tokenizer_explain_fuzzy(lang: str, sentence: str) -> None: """ Tests whether output of tokenizer.explain() matches tokenizer output. Input generated by hypothesis. lang (str): Language to test. text (str): Fuzzily generated sentence to tokenize. """ tokenizer: Tokenizer = spacy.blank(l...
5,293,973
def calc_acc(fn: float, fp: float, tp: float, tn: float) -> float: """ :param fn: false negative miss :param fp: false positive or false alarm :param tp: true positive or hit :param tn: true negative or correct rejection :return: accuracy """ return (tp + tn) / (tp + tn + fn + ...
5,293,974
def errors(all_jobs=False): """Get error messages from the cluster. Args: all_jobs: False if we should only include error messages for this specific job, or True if we should include error messages for all jobs. Returns: Error messages pushed from the cluster. This ...
5,293,975
def main(args): """ TODO: Populate docstring with --help readable information """ # TODO: Populate docstring #/* ----------------------------------------------------------------------- */# #/* Print usage #/* ----------------------------------------------------------------------- */# ...
5,293,976
def _gen_test_tree_4(): """ Not BST 5 3 9 2 10 6 8 """ tree = BinaryNode(5) tree.left = BinaryNode(3) tree.left.left = BinaryNode(2) tree.left.right = BinaryNode(10) tree.right = BinaryNode(9) tree.right.left = BinaryNode(6) tree.right.right = BinaryNode(8) r...
5,293,977
def by_circ(x, y): """ Sort circRNAs by the start and end position """ return x.end - y.end if x.start == y.start else x.start - y.start
5,293,978
def get_rest_of_manifest_values(): """ If an existing manifest is present then we do not want to overwrite any fields the user may have filled out. So we want to read in everything but the resources: section and use that when generating the file. """ stream = open('hardening_manifest/hardening_manifest....
5,293,979
def ConvertJsonIntoDict(string): """Read a JSON string and convert its contents into a Python datatype.""" if len(string) == 0: print >> sys.stderr, ('Error could not parse empty string') raise Exception('JSON data missing') try: json = simplejson.loads(string) except ValueError, e: print >> sy...
5,293,980
def process_html(body): """Transform a screen-optimized HTML body to a mail-optimized one. Relies on :class:`premailer.Premailer` to include styles in HTML body and optimize content. Args: body (str): The HTML string to process. Returns: :class:`str`: The processed HTML mail body....
5,293,981
def img_crop(img, length, cx=None, cy=None): """ Crop the image to square (length^2). If cx and cy are not specified, it will set to where the max pixel count is. I: plt.imread() length: pixel sizes cx, cy: center pixel of the image """ if not (cx and cy): cy, cx = unravel_index(...
5,293,982
def post_special(url, param: dict = None): """ 发送 post 请求,主要是参数中的ddjm等参数,可能用于防火墙拦截 :param url: url :param param: param dict :return: 返回json中的data域 """ param_json = COMMON_PARAMS.copy() param_json.update(param if param is not None else {}) response = requests.post(url, json=param_json...
5,293,983
def nogc(func): """disable garbage collector Python's garbage collector triggers a GC each time a certain number of container objects (the number being defined by gc.get_threshold()) are allocated even when marked not to be tracked by the collector. Tracking has no effect on when GCs are triggered,...
5,293,984
def evaluate_f1_update_confusion_matrix(df, new_rule, class_col_name, counts, min_max, classes): """ Computes the F1 score of the dataset for a given set of rules using leave-one-out cross-evaluation. Assumes that the initial confusion matrix already exists, hence evaluate_f1_initialize_confusion_matrix() s...
5,293,985
def test_examples(): """Test approximately the examples in the README.""" example = "python\nsnake\nss\nmagpy\npiethon\nreadme.md\n" compare_command(example_cmd="cut -c1-4", pyp_cmd="pyp 'x[:4]'", input=example) compare_command( example_cmd="wc -c | tr -d ' '", pyp_cmd="pyp 'len(stdin.read())'...
5,293,986
def forward(model, generator, return_input=False, return_target=False): """Forward data to a model. Args: model: object generator: object return_input: bool return_target: bool Returns: audio_name: (audios_num,) clipwise_output: (audios_num, classes_num) ...
5,293,987
def corrfun_mat(image_dict): """ A useful fixture containing the correction function evaluated over the range of the sky plane test image. """ ra = image_dict["ra"] dec = image_dict["dec"] # pre-multiply the image by the correction function return spheroidal_gridding.corrfun_mat(np.fft.ffts...
5,293,988
def get_nft_info_from_puzzle(nft_coin_info: NFTCoinInfo) -> NFTInfo: """ Extract NFT info from a full puzzle :param nft_coin_info NFTCoinInfo in local database :return: NFTInfo """ uncurried_nft: UncurriedNFT = UncurriedNFT.uncurry(nft_coin_info.full_puzzle) data_uris: List[str] = [] fo...
5,293,989
def try_import(name, alternative=None, error_callback=None): """Attempt to import a module, with a fallback. Attempt to import ``name``. If it fails, return ``alternative``. When supporting multiple versions of Python or optional dependencies, it is useful to be able to try to import a module. :...
5,293,990
def fix_masks(masks, indices): """Remove from every mask any common pixels with another mask""" new_masks = [] for ind in indices: mask = masks[ind] for ind1 in indices: if ind != ind1: mask = np.logical_and(mask, np.logical_and(masks[ind], np.logical_not(masks[in...
5,293,991
def test_dask(): """Test Histogram2D with dask arrays.""" x_axis = pyinterp.Axis(np.linspace(-180, 180, 1), is_circle=True) y_axis = pyinterp.Axis(np.linspace(-80, 80, 1)) hist2d = pyinterp.Histogram2D(x_axis, y_axis) x = da.full((4096 * 8, ), -180.0, dtype="f8", chunks=4096) y = da.full((4096 ...
5,293,992
def iterParents(task): # pragma: no cover """Get all the parents of a task, including the task itself.""" eachTask = task while eachTask is not None: yield eachTask # Note: until we call `get()`, we have some sort of thunk. We cannot # decide whether it's null or not until we evalua...
5,293,993
def barnsley_fern(range_x: Sequence[float], range_y: Sequence[float], steps: int = 20, samples: int = 20000 ) -> tuple[np.ndarray, np.ndarray]: """Generates a Barnsley Fern Args: init_x: x coordinates of the starting points init_y: y coordinates of the starti...
5,293,994
def prepare_nginx_dirs(source_dir): """ Добавление директорий установки nginx :param source_dir: :return: """ with open('{}/nginx.dirs'.format(source_dir), 'r') as input_file: content_file = input_file.readlines() with open('{}/nginx.dirs'.format(source_dir), 'w') as output_file: ...
5,293,995
def getoutput(cmd): """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' ...
5,293,996
def takearg(argv): """ Function which record arguments from the command line.""" # default values masked = False # freq 0,1 and 1,0 masked if masked = 1 pts_l = None # Grids sizes for extrapolation outputname = "mis_fs_2d_optlog" model_list = ["PAN","PANG","PANGb","PANbG","PAN2N","PANG2N","PANG...
5,293,997
def handle_choice(uid): """ This function handles the choice of the user. """ print("Type 'Back' to go back.") choice = input("Enter Code > ") if choice.lower() == "back": show_menu(uid) else: return search_for_choice(uid, choice)
5,293,998
def main(args: Namespace) -> None: """Run the main program. Arguments: args: The object containing the commandline arguments """ config = load_config(args.config) # Automatically implements frame skipping internally env = gym.make("Pong-v4", frameskip=config.frame_skips) if config...
5,293,999