content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from typing import List def _check_antonymy(antonym_library: Dict[str, List[str]], attr_value1: 'AttributeValue', attr_value2: 'AttributeValue') -> Dict[str, str]: """ Check if there are any shared antonyms within the two values Parameters ...
a4cfca502d99b35a60fd78f2b8a4a4e20453f187
3,624,767
def innerip(funcname): """获取内网IP逻辑""" inner_ip = get_ip_address('eth0') return inner_ip
daff3e1b994e3e24297517c615f27f5978d0ca75
3,624,768
def create_single_choice_question(text, choices, topic_id=None, scenario_id=None): """ Create a single choice question for either a topic *or* a scenario. Parameters ---------- text : str Body of the question. choices : list List of question choices. It must be a list of...
5645db0fd77b5f265d9906927f905dfb984f31d6
3,624,769
def render_cmdhelp_border(term: Terminal) -> str: """Render border around cmdhelp box""" return render_border( start_x=const.CMDHELP_X, start_y=const.CMDHELP_Y, height=const.CMDHELP_HEIGHT, width=const.CMDHELP_WIDTH, title=" Help ", term=term, )
86b938476982f3c7853cabd382dd83d49381504c
3,624,770
import pandas def drop_child_cases(pcts, keep_child_entitlements=True): """ Drop all child cases from a PCTS extract (as indicated by them having a parent case listed). Parameters ========== pcts: pandas.DataFrame A PCTS extract of the shape returned by subset_pcts. keep_child_e...
2f4e0fb90a7d093342502e802d9818674960ce37
3,624,771
def reopen_gap(decanonicalized: BlockNumber, base_gaps: ChainGaps) -> ChainGaps: """ Add a new gap, for a header that was decanonicalized. """ current_gaps, tip_child = base_gaps if tip_child <= decanonicalized: return base_gaps new_raw_gaps = current_gaps + ((decanonicalized, decanoni...
2c8d7fd24a528d64ddb6f81a02a89b3284e6dde4
3,624,772
def is_std_wstring(type_): """ Returns True, if type represents C++ `std::wstring`, False otherwise. """ if utils.is_str(type_): return type_ in wstring_equivalences else: type_ = remove_alias(type_) type_ = remove_reference(type_) type_ = remove_cv(type_) r...
7d223f6290db220250c709f5ea9de810d0fc175d
3,624,773
def alternating_havel_hakimi_graph(aseq, bseq, create_using=None): """Returns a bipartite graph from two given degree sequences using an alternating Havel-Hakimi style construction. Nodes from the set A are connected to nodes in the set B by connecting the highest degree nodes in set A to alternatively...
72f332a05595163a119dd54d6d3e40cb7763e947
3,624,774
import io def write_conformers(mol_input, mol_reference, conf_file): """ Generate conformer and calculate rmsd wrt reference """ top_rmsd = -1 conformer_generator = conformer.ConformerGenerator() conformer_generator.settings.superimpose_conformers_onto_reference = True conformers = conform...
0513d92699220d3b9fed9a3b6828aa19b22ae51b
3,624,775
def get_stdout(): """Return the redirected stdout in the current context.""" return _get_context().get(REDIRECTING, {}).get('stdout')
f6a0b66d98f763e53702005b031454b6f1aede3f
3,624,776
from typing import List def _get_ner_tags_and_mask(current_instance: Instance, input_field_to_attack: str, ignore_tokens: List[str]): """ Used for the NER task. Sets the num_ignore tokens, saves the original predicted tag and a 0/1 mask in the position...
3d496adea05576fe4fb06d1b4912e99d08a01d22
3,624,777
import pandas as pd def get_employees(filepath): """ takes a Toolbox csv filepath, retrieves it and exports as dataframe """ if not filepath: print("Please provide a Toolbox filepath to 'employees.csv'") return try: df =pd.read_csv(filepath, usecols=['employeeID','mail','h...
e327199867ad66021686185460b884eedacc60c1
3,624,778
def normalize_spec(value: t.Any) -> "TypeSpec": """normalize tensor spec""" if not _isinstance_wrapper(value, TENSOR_CLASS_NAMES): return value if _isinstance_wrapper(value, "RaggedTensor"): return tf.RaggedTensorSpec.from_value(value) if _isinstance_wrapper(value, "SparseTensor"): ...
831af3da7fc1e36966dd424ae42f40826ff50364
3,624,779
def get_cost(state): """Calculates cost/fitness for the solution/route.""" distance = 0 for i in range(len(state)): from_city = state[i] to_city = None if i+1 < len(state): to_city = state[i+1] else: to_city = state[0] distance += data.get...
89e8539c4cfd7ade46f3db634c16e8a8dd5932c8
3,624,780
import warnings def fit_decision_tree(printscore=False): """ This function fits sklearn's decision tree classifier on the college dataset and returns the model The data values are first scaled using MinMaxScaler and then split into train and test sets before using for fitting ML model """ ...
3a23230f4fcf4770f2897393fc933f7fe75add08
3,624,781
def parse_info(file_path, counter=1, verbose=True): """ Grab html code from a file and parse for information - return dict of dicts. """ this_counter = counter # Open file and parse with BS4 with open(file_path, "r") as f: soup = bs(f.read().decode("utf-8"), "lxml") # Get category cate...
e88bb52512a165dbeb02c24bb5d0430181eed0d4
3,624,782
def describe(profile, description): """ Generate a query by describing it as a series of actions and parameters to those actions. These map directly to Query methods and arguments to those methods. This is an alternative to the chaining interface. Mostly useful if you'd like to put your queries...
b6ef8fef9f0443d78cd9236212d84962484d785a
3,624,783
def get_filenames_request(products, download_directory): """Get local files url corresponding to a Copernicus request (must be already downloaded). :param products: (dict) Copernicus Hub query :param download_directory: (str) Url of folder for downloaded products :return: (list) List of strings with lo...
5591948ce2445399d06da6c84f3fe1f6b8b4b128
3,624,784
def home(): """Home endpoint that redirects to docs""" return RedirectResponse("/docs")
97e75427ea23670ca7a4ce5e4022cb26acde1c30
3,624,786
def check_bandpass_biquad(method): """Wrapper method to check the parameters of BandpassBiquad.""" @ wraps(method) def new_method(self, *args, **kwargs): [sample_rate, central_freq, Q, const_skirt_gain], _ = parse_user_args( method, *args, **kwargs) check_biquad_sample_rate(samp...
22bb19470c33d4cf6972c63e1f65a5d788869643
3,624,787
def get_cached_ip(): """ Retrieve Cached IP From File, cuts down on API requests if IP Address hasn't changed. Returns: cached_ip: Cached IP or 0 to force refresh of public IP """ try: cached_file = open(CACHE_FILE_PATH, 'r') cached_ip = cached_file.read() cache...
b172b0bfedc7d93e3771ea00e52d4664e0e27d6e
3,624,788
def map_box_to_image(box, proj_mat): """ Projects 3D bounding box into the image plane. Args: box (Box3D) proj_mat: projection matrix """ # box in camera coordinate points_3d = box.in_camera_coordinate() # project the 3d bounding box into the image plane points_2d = proj...
43c93c67f9314a3f786812c4aa3e02eb6bb6bb7c
3,624,789
def loadCache(fname): """ Loads a pickle file from a filename and returns the resulting data. @param fname: Filename to load @return: data retrieved from file """ try: data = util.file_pickle_load(fname) except Exception: raise RuntimeError("Could not read %s" % fname) r...
0ee4ecf0c59d80c12eaf940f05bd4d14928956ad
3,624,790
def max_pool(inputs, size=-1): """max_pool downsamples a feature map.""" if not inputs[1]: x_input = inputs[0][0] else: x_input = sum_op(inputs) if size in [3, 5, 7]: return tf.nn.max_pool(x_input, ksize=[1, size, size, 1], strides=[1, 1, 1, 1], padding='SAME') else: ...
302752663da0f706ac38d08918603ddcc706cd40
3,624,791
def _repo_choices(repos_map=None): """Make up repo choices. """ if repos_map is None: repos_map = fleure.globals.REPOS_MAP rss = [[(k, v) for v in vs] for k, vs in repos_map.items()] return fleure.utils.uconcat(rss)
f4e607e81c2405a8a1630c8685fb8832506bb7b5
3,624,792
def grid_plot(filename, slice_index=0, axes=None, title="", vmin=None, vmax=None, rel_smoothing_scale=None, filename2=None, factor=1., boxsize=None, colorbar=True, fix_colorbar=True, v_ratio=False, factor_minus_allowed=False, cmap=None, norm=None, log_cbar=False, ...
1d2d29b0f3c90feb0919a07546de4efec5e07ba9
3,624,793
def get_overrides(_conf=None): """ Read the configuration file and look for ceph-medic sections and flags to set the defaults, these are later checked by the main method to see if any need to be overridden *again* if specified on the CLI directly. """ # Get the subcommand name to avoid overwritt...
7d6db52f97a425c6dcd39ceb7c4803579003f34b
3,624,794
def left_hist_data(hotel_type="All", year=2016, month=1): """returns a data frame containing binned counts of hotel guests' country of origin for the selected hotel type and time period Parameters ---------- hotel_type : string, either "City", "Resort", or "Both year: the year selected f...
a4aa27cadeda67771165a7ff4fd785c282dfb063
3,624,796
import calendar from datetime import datetime def get_first_day_next_month(day): """ Returns the next month given the current day :param day: :return: """ last_day = calendar.monthrange(day.year, day.month)[1] one_day = datetime.timedelta(days=1) return datetime.date(day.year, day....
8761477b28f59b2cbdf583114493a1af769f0d7a
3,624,797
import yaml def ensure_namespace(ctx): """创建命名空间""" k8s_client = K8SClient(ctx) def _add_token_to_ctx(k8s_client, ctx): # 获取service_account_token try: ctx["service_account_token"] = get_service_account_token(k8s_client) except Exception as error: logger.err...
943757653be64a8d648b810d80c90b0d17bac941
3,624,798
def dates(min_year=None, max_year=None): """Return a strategy for generating dates. .. deprecated:: 3.9.0 use :py:func:`hypothesis.strategies.dates` instead. All generated dates will be between min_year and max_year, inclusive. """ note_deprecation('Use hypothesis.strategies.dates, which s...
09d0c13e93eb30091356ac89179ba63c12eccbb6
3,624,799
import math def _get_top_left_coordinates(height, width, patch_size): """Calculate coordinates of top-left corners for patches.""" n_h = math.ceil(height / patch_size) n_w = math.ceil(width / patch_size) tops = np.linspace(0, height - patch_size, n_h, dtype=int) lefts = np.linspace(0, width - pat...
b825f4829d49ab648484a6ebcfb0af1094f613b7
3,624,800
def create_stream(data_type, transaction_id): """ Construct a 'createStream' message to issue a new stream on which data can travel through. :param data_type: int the RTMP datatype. :param transaction_id: int the transaction id in which the message will be sent on. """ msg = {'msg': data_type, ...
6ceb6f259c590bdb21589c57ba053fad5c7e1851
3,624,801
import math def pdg_case ( error ) : """Classify according to PDG prescription - see http://pdg.lbl.gov/2010/reviews/rpp2010-rev-rpp-intro.pdf - see section 5.3 of doi:10.1088/0954-3899/33/1/001 The basic rule states that - if the three highest order digits of the error lie between 100 and 35...
d43d4b3aed3c814d77ba0477e856f9ec04486fd1
3,624,802
def _version_string_to_tuple(version_string): """Convert a version_string to a tuple (major, minor, patch) of integers.""" return (int(n) for n in version_string.split('.'))
d2fe2a3d9f6f23d1d80c2808436386c18893828f
3,624,803
def build_averaged_flowgram(flowgrams): """Builds an averaged flowgram from a list of raw signals.""" result=[] if(len(flowgrams)==1): return flowgrams[0] for tuple in map(None, *flowgrams): k=0 sum=0 for element in tuple: if (element!=None): ...
f2ea94478280d51139b64badcbb98cfece3b61d0
3,624,805
def flatten(request, root, write): """ Incrementally write out a string representation of C{root} using C{write}. In order to create a string representation, C{root} will be decomposed into simpler objects which will themselves be decomposed and so on until strings or objects which can easily be co...
c92d8bb889d58ab382b207185f9190566bfcda9d
3,624,807
def get_dates(dates): """Returns a list of dates date format: yyyy-mm-dd input can be a single date or a list of two (start and end date) """ ans_list = [] if not isinstance(dates, (list, tuple)): dates = [dates] if len(dates) == 1: try: validate_date(dates...
212d4c18032f661831b24ac794525efbce5b1999
3,624,808
def register_op_attr(op_name, attr_key, value=None, level=10): """Register an operator property of an operator by name. Parameters ---------- op_name : str The name of operator attr_key : str The attribute name. value : object, optional The value to set level : in...
ef469099d7b27956a9b123c5b368efb561a9c30b
3,624,810
def posix_mkfifo(space, fname, mode): """ posix_mkfifo - Create a fifo special file (a named pipe) """ try: os.mkfifo(fname, mode) return space.newbool(True) except OSError, e: space.set_errno(e.errno) return space.newbool(False)
921ea6c6b11546428611f4a94aa66eec8caf452f
3,624,811
def validateProof(target_hash, proof): """Core validation utility Validates the inserted proof by comparing to the provided target hash, modifies the proof's status as ``True`` or ``False`` according to validation result and returns this result :param target_hash: the hash to be presumably attained at...
8538d0d5d1b1b27d2668cb127a9451d328fa786f
3,624,813
import re def get_major_version(version): """ Enable checking that 2 versions are within the same major version """ components = re.findall(r"\d+", version) major = components[0] return major
b3d017b3dbe49b0a30d9919272906e8936c14f83
3,624,814
def calc_intersection_PAL(xy_1_a, xy_1_b, xy_2_a, xy_2_b): """ Calculates intersection points of the polygonal audience lines This function is necessary for the handling of gaps in the audience lines and is used to create the non-audience lines. Calculation of the intersection of two adjacent sectio...
f1ec81b1ac973c7c80427e386d919d6a47c04729
3,624,815
import json def delete(rt_info): """ 删除rt的mysql存储相关配置 :param rt_info: rt的配置信息 :return: rt的mysqls存储清理结果 """ # 对于mysql中表删除,考虑通过rename表名,在尾部标记to_delete,然后定期清理的方式 mysql = rt_info[STORAGES][MYSQL] physical_tn = mysql[PHYSICAL_TABLE_NAME] ptn_arr = physical_tn.split(".") conn_info = ...
2612e2bd529398176c56398804bf7c654066bb7d
3,624,816
def create_person_ruler(nlp: Language) -> EntityRuler: """Create entity ruler that extracts person name with regex. Notes: This component must be used with `camphr.lang.mecab.Japanese`. In order to imporove accuracy, it is recommended to create a Mecab user dictionaly. See scripts/mecab_person_...
d217fda4c20827f42c9ef56f2a7021d58f571b13
3,624,817
def to_pixel_samples(img): """ Convert the image to coord-RGB pairs. img: Tensor, (3, H, W) """ coord = make_coord(img.shape[-2:]) rgb = img.view(3, -1).permute(1, 0) return coord, rgb
1a63e6e1b533608949921d247d90bb967365c924
3,624,818
def inverse_transform(X, scaler, trend=None): """ :param X: the data :param scaler: the scaler that have been used for transforming X :param trend: the trebd values that has been removed from X. None if no detrending has been used. It has to be the same dim. as X. :return: X with tre...
aebb52543896dc551329f57ea8e389d93f376d36
3,624,819
def get_available_snapshots(session, identifier, snapshot_type=None): """Returns snapshots in the available state for a given DB or Cluster `identifier`. Args: session (:class:`boto.rds2.layer1.RDSConnection`): The RDS api connection where the database is located. identifier (str): T...
046e5949c73542ea73d51b90b91cf1d676ab7778
3,624,820
from typing import Any def is_action(value: Any) -> bool: """Returns ``True`` if the value is an action.""" return isinstance(value, dict) and "action" in value
46c691c7afd221c0f77869428535f6b943332905
3,624,821
def get_parse_args_definitions(wanted=None): """ Parse the args the script neeeds :param: wanted: list of args the application will use :returns: A list with the options for the wanted args """ definitions = { 'kolibri_dev': [ '-kd', '--kolibri-dev', { 'requir...
9215b13917652fe23c053f24ec3ce42b1a9fd924
3,624,822
import base64 import re def _create_machine_azure(conn, key_name, private_key, public_key, machine_name, image, size, location, cloud_init, cloud_service_name, azure_port_bindings): """Create a machine Azure. Here there is no checking done, all parameters a...
5fb31ef31da7b547418f12556fdf9b1c4091808a
3,624,823
def euclidean_distance(q1, q2): """Returns Euclidean distance between arrays q1 and q2.""" diff = ravel(q1 - q2) return sqrt(sum(diff*diff, axis=0))
7383e1fb8e561c5c1ad598f0262bb89e4ba9a3be
3,624,824
def merge(root, *others): """Combine a bunch of dictionaries and return the result""" cp = clone(root) [cp.update(other) for other in others] return cp
7efd17ca14c320d282921e63cdcd8ad063d64fb0
3,624,825
from typing import OrderedDict def read_config(config_file, default_config=None): """ Return a dictionary with subdictionaries of all configFile options/values """ config = SafeConfigParser() config.optionxform = str config.read(config_file) sections = config.sections() dict1 = Ordered...
e115d4912e33d689cb1a8e633a7a0c1c0949641c
3,624,828
def source_status(request): """ Source availability status endpoint for Platform Sources to get cost management source status. Parameter: source_id corresponds to the table api_sources Returns: status (Dict): {'availability_status': 'unavailable/available', 'ava...
07d949e609e67497b378a34a5f0d0935675c6b8a
3,624,829
def name_to_components(name): """Converts a name to a list of components. Arguments: name - Name in the format /name1=value1/name2=value2/.. Returns: list of (name, value) tuples """ ret = [] components = [x for x in name.split('/') if x] components = [x.split('=') for x in componen...
5683e3c4fdce53b53431484a46cd23c8959d20a2
3,624,831
def multiple_testing_correction(ps, alpha=0.05, method='benjamini-hochberg', **kwargs): """ correct pvalues for multiple testing and add corrected `q` value :param ps: list of pvalues :param alpha: significance level default : 0.05 :param method: multiple testing correction method [bonferroni|benjamini...
cf853a9e7369550d1986b3139ea0e5131dd21437
3,624,833
def detect_format(filename): """Return the name of the format based on the start of the file.""" enough_bytes = 0x1000 with open(filename, 'rb') as f: data = f.read(enough_bytes) if isinstance(data, bytes): data = data.decode(errors='replace') if data.startswith('DRCOV VERSION: 2'):...
ab66158c19cb99150d0b01ed57613bd26c8006c2
3,624,834
from typing import Optional import readline def clear_tab_complete_vocabulary() -> None: """ Resets vocabulary used for tab completion. It's important to either use the cleanup argument in tab_complete, or call this function after setting a vocabulary. This will prevent irrelevant options displaying when ...
2014e996474742d956566cc95887ba4c868398a6
3,624,835
from datetime import datetime def _cache_filename(url): """yyyy-mm-url-slug.json""" today = datetime.utcnow().strftime("%Y-%m") slug = slugify(url) filename = CACHE_DIR / f"{today}-{slug}.json" return filename
43cce02ff72d890382219fdc6fdf08cb95cfcc03
3,624,836
import re def fixupAnchor(anchor): """Miscellaneous fixes to the anchors before I start processing""" # This one issue was annoying if anchor.get("title", None) == "'@import'": anchor["title"] = "@import" # css3-tables has this a bunch, for some strange reason if anchor.get("uri", "").st...
ba352cc5b18f82000be3943cf03db8ebcb41ddff
3,624,837
def deep_merge(base, updates): """ apply updates to base dictionary """ for key, value in updates.iteritems(): if key in base and isinstance(value, dict): base[key] = deep_merge(base[key] or {}, value) else: base[key] = value return base
6add1c048368f1547aa6ce5ebea1fe17b373fb87
3,624,838
def load_vocab_dict(vocab_file): """Returns a dictionary and the vocabulary size.""" def count_lines(filename): """Returns the number of lines of the file :obj:`filename`.""" with open(filename, "rb") as f: i = 0 for i, _ in enumerate(f): pass ...
2331e3472af1b538defef9a41539da2b1ae687c3
3,624,839
import collections def with_concurrency_limit( bucket_id: str, /, *, error_message: str = "This resource is currently busy; please try again later.", ) -> collections.Callable[[CommandT], CommandT]: """Add the hooks used to manage a command's concurrency limit through a decorator call. .. war...
e51801c21667fd72b532429a4c82412333e59d84
3,624,840
def request_oauth_token(): """ Prompts user for credentials and returns Oauth token from GitHub """ print "Requesting an oauth token from GitHub." print "Your username and password will not be stored." username = raw_input("GitHub Username: ") password = getpass.getpass("GitHub Password: ") try: g = ...
4312944dbe9c3cb6c32920a625aacbed29f646a7
3,624,841
def preprocessor(normalization="auto", assume_immutability=False, renormalize=False): """ Wrapper function that generates lambda expressions for the method to_sparse_matrix. Args: normalization: Normalization parameter for `to_sparse_matrix` (default is "auto"). assume_immutability: If True, th...
fdf207ba55bf2679a7a22aba482d1d90e1f09212
3,624,842
def bar_facets_from_pivoted_df(not_pivoted_df, plot_x, plot_y, order_list, color_list, filename=None, portrait=True): """ General function to produce faceted plots (O2 vs rep or vice versa) given already-pivotd data. :param not_pivoted_df: a dataframe that will be pivoted...
c62e86efbdff9a3c0217db85bdec882d13ee4cd3
3,624,843
def jax_issue_role(name, rawtext, text, lineno, inliner, options=None, content=()): """Generate links to jax issues or PRs in sphinx. Usage:: :jax-issue:`1234` This will output a hyperlink of the form `#1234 <http://github.com/google/jax/issues/1234>`_. These links work even for PR...
6830183d70c8aa85da7a5775e22b32efacf92066
3,624,844
def planckwavenum(waven, Temp): """ input: wavenumber (m^{-1}), Temp (K) output: planck function in W/m^2/m^{-1}/sr """ Bwaven = c1 * waven**3. / (np.exp(c2 * waven / Temp) - 1) return Bwaven
96e179b280c96d7939deb9f3f2e9f82e862786bb
3,624,845
from typing import Dict def validate_name_request(filing: Dict, filing_type='registration') -> list: """Validate name request.""" nr_path = f'/filing/{filing_type}/nameRequest/nrNumber' nr_number = get_str(filing, nr_path) msg = [] # ensure NR is approved or conditionally approved try: ...
0019af0fea14869afd1634ee480ed77986548227
3,624,846
def wasserstein_hinge_discriminator_loss( discriminator_real_outputs, discriminator_gen_outputs, real_weights=1.0, generated_weights=1.0, real_hinge=1.0, generated_hinge=1.0, scope=None, loss_collection=tf.compat.v1.GraphKeys.LOSSES, reduction=tf.compat.v1.losses.Reduction.SUM_BY_NON...
30ee18fee8b7aaaaebcce8100f03fd2f8b719b01
3,624,847
from typing import Dict from typing import List def dict_to_hfdataset(dic: Dict[str, List]) -> HFDataset: """helper function to convert to huggingface's dataset class """ return HFDataset.from_dict(dic)
ea777577f5c5922b21891c21cfdb990838e2f5a5
3,624,848
from pathlib import Path def experiment_fixture(): """'experiment--test' in tmpdir. Returns Experiment object.""" exp_path = Path(__file__).parent / "fixtures" / "experiment--test" return Experiment(str(exp_path))
7278c2c14327907795f00e43c637a647161afaab
3,624,849
def PostScriptDC_GetResolution(*args): """ PostScriptDC_GetResolution() -> int Return resolution used in PostScript output. """ return _gdi_.PostScriptDC_GetResolution(*args)
2d8fb7f1a2ebc39e737b763a1736898648cd5307
3,624,851
def find_indices(x, y): """ Find the index of every element of y in x """ # indices that would sort x (length x) index = np.argsort(x) sorted_x = x[index] # index of every element of y in sorted x (length y) # can't plug this into either x or y: # it's too short for x (being leng...
37c46ae07b1d48a7e5e3e0e89b18976342ea6679
3,624,852
def load_data(filepath) -> DataFrame: """Load dataset from file. Extract datasets and category names Args: filepath (str): user level file path Return: df (DataFrame): DateFrame """ df = spark.read.csv(filepath, header=True, inferSchema=True) return df
570d562eb53acfa39d7a4080780e137fe4e4e66e
3,624,853
def get_storage_type(storage_path): """Get storage type for a storage path (local and supported remote storages)""" for storage_type in storage_prefex_config: if storage_path.startswith(storage_prefex_config[storage_type]): return storage_type raise StorageNotSupported("Storage path type...
c2163556d3b2fc8f09ed994d5fd91f4cd7c829df
3,624,854
def delete_article(id): """ A view function for administrators to delete an articles. """ article = Article.query_by_id(id) article.delete() flash(f"Article id {id} deleted", "success") current_app.logger.info(f"{str(article)} deleted.") return render_template("result.html", url=url_for(...
5113e782a8dbf91dd30448808b61a4d700b46e94
3,624,856
def smooth_serie(dfi): """Smooth a serie by doing a time_average 2 times""" df = time_average(dfi, months=12, center=True) return time_average(df, months=6, center=True)
e13a8d34625a73d42e871c815065442c3213f621
3,624,857
def create_ast_dict(commits, repo_path, repo_name, g): """ Creates a dictionary mapping the SHA1 of each version in `commits` to a node object that contains the abstract syntax trees of all the Python code in that version. :param commits: the list of commits in a repo :type commits: Git.Commit ...
d952d7db704887845fb0662b3cefcf49a5ad7a8d
3,624,858
from typing import Optional def get_license(license: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLicenseResult: """ Returns the specified License resource. *Caution* This resource is intended for use only by t...
370f1cba868c448746220512c38ea3e31d22a780
3,624,860
def tjmaxx(tjmaxx_url: str) -> dict: """Scrape product information from Tjmaxx Keyword arguments: tjmaxx_url -- a product url from tjmaxx.tjx.com """ tjmaxx_product = _tjmaxx._tjmaxx(tjmaxx_url) return tjmaxx_product
d319a6ec195db7b518dd51b200e66b96c2461f18
3,624,861
def _top_N_similar(source_inds, source_mat, target_mat, n, exclude_mat_sp=None, source_biases=None, target_biases=None, simil_mode='cosine'): """ for each row in specified inds in source_mat calculates top N similar items in target_mat :param source_inds: indices into s...
6bd5e7db4bc1ed717db3504535babc7b9be84704
3,624,862
import io def spawn_compressor(exe, filename, mode, buffering=-1, encoding=None, errors=None, newline=None): """Spawn a subprocess to run a (de)compressor like gzip or bzip2. Args: exe (str): executable file name (must be fully qualified or found on the current PATH) filename (str or file obj...
d8b8390ac2002d7b408db41c7df180578a815a1a
3,624,863
def rgrids(radii=None, labels=None, angle=None, fmt=None, **kwargs): """ Get or set the radial gridlines on the current polar plot. Call signatures:: lines, labels = rgrids() lines, labels = rgrids(radii, labels=None, angle=22.5, fmt=None, **kwargs) When called with no arguments, `.rgrids` ...
a7e4c936994ba89474751c3837ffd78c53f800d6
3,624,865
def connect_to_cloudfiles(region=None, public=None): """Creates a client for working with CloudFiles/Swift.""" if public is None: is_public = not bool(get_setting("use_servicenet")) else: is_public = public ret = _create_client(ep_name="object_store", region=region, public=is...
47aa0b3c34918744844754754d3685180a0d3e7a
3,624,866
def vec_init(seq, amino_acid): """ This function is for initialize feature stats table """ bi_gram = {} for acid_1 in amino_acid: for acid_2 in amino_acid: temp_1 = acid_1 + acid_2 bi_gram[temp_1] = 0 pos_list = pos_init(seq, amino_acid) for pos_motif in pos...
16418e67cd216c657ccc5668c58dd4e153c02891
3,624,867
def has_trailing_character_return(str_multiline: str) -> bool: """ >>> has_trailing_character_return('jhgjh\\n') True >>> has_trailing_character_return('jhgjh\\ntestt') False """ if len(str_multiline) and str_multiline[-1] == '\n': preserve_trailing_linefeed = True else: ...
21e6a7c9bb76e37ee05ed61b2012ec3a92413540
3,624,870
def get_short_help_from_long(val): """ Extracts 100% of the help - except for the details section within option descriptions. Rules: 1. Sections of options are defined by having the string "Options: " within the first thirty characters of the line. The section ends with a blank ...
60d77f119dffaa68e81b7743da309a6a5ecd1912
3,624,871
from typing import Any from typing import List import importlib def decorate_function_view(view: Any, decorators: List[str] = None) -> Any: """ Similar to :func:`.decorate_class_view`, but for function based views """ if not decorators: decorators = [] for decorator in decorators: ...
d4ecf01d3220e425288d0faf9b7e587b57fcc181
3,624,872
def linenos(f): # type: (FunctionType) -> Set[int] """Get the line numbers of a function.""" return {instr.lineno for instr in Bytecode.from_code(f.__code__) if hasattr(instr, "lineno")}
80e518d08d635b920098599787b6b8a8f401e727
3,624,873
from typing import Callable def firm_up(t: Callable[[np.ndarray], np.ndarray], alpha: float=0.5) -> Callable[[np.ndarray], np.ndarray]: """converts given nonexpansive mapping into a firmly nonexpansive mapping whose fixed point coincides with the given one. This implementation is based on the property of the ...
b5577d5b2d0d92a1763584efac86c7d6263414e8
3,624,874
def proposal_trusted(proposal_appid: Expr, trust_assetid: Expr): """ Check that the proposal is trusted (has been assigned a Trust token) """ trusted = AssetHolding.balance(appaddr(proposal_appid), trust_assetid) return Seq([ trusted, Return(And(trusted.hasValue(), trusted.value() > ...
a62572e519583ebcbb66b0bfe3aca673fc977d1d
3,624,875
def get_genotype(read, ref_position, snp_position, cigar_tuple): """ Input read position, read sequence, SNP position, cigar Return the base in read that is aligned to the SNP position """ cigar = { # alignement code, ref shift, read shift 0: ["M", 1, 1], # match, progress both 1: ["...
bf6b212b318ab8425124bbdd40d5ab54d05e8858
3,624,876
def inc_preemptible_resource(preemptible_resource_port, expr, stream_port): """Increase the count of available resource by the specified number, invoking the awaiting and preempted processes according to their priorities as needed.""" r = preemptible_resource_port e = expr s = stream_port expect_pre...
0929100e9a5e1e584f9bf47dad2fb50afaa8644c
3,624,877
def selu(a: TensorLikeType, inplace: bool = False) -> TensorLikeType: """ Reference implementation of torch.nn.functional.selu """ if inplace: raise NotImplementedError alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 rhs = refs.mul(alpha, refs.e...
25e0401d22e75615f7e6b565a92716173fe005a0
3,624,878
def get_blowout_properties(): """ Return the properties for the base blowout case Return the fluid properties and initial conditions for the base case of a blowout from the Model Inter-comparison Study for the case of 20,000 bbl/d, 2000 m depth, GOR of 2000, and 30 cm orifice. """ ...
1521c62fac787e10ca6e7beaa356c82914043cc8
3,624,879
def strtobool(val: str) -> bool: """Convert a string representation of truth to True or False. True values are 'y', 'yes', 't', 'true', 'on', and '1'. False values are 'n', 'no', 'f', 'false', 'off', '0' and ''. Raises ValueError if 'val' is anything else. """ match val.lower(): case "y...
f78c8aed3b9be896847c9a56de59de550b3f5381
3,624,880
import random def clustering_kmember(data, k=25): """ Group record according to NCP. K-member """ clusters = [] # randomly choose seed and find k-1 nearest records to form cluster with size k r_pos = random.randrange(len(data)) r_i = data[r_pos] while len(data) >= k: r_pos = fi...
8e8daaf6c9e952617def89124b62fdda4f6731f2
3,624,881
import torch def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] """ height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_h...
a10380c4a80de52bf7145fe134e12e49b5cf66a6
3,624,882