content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def conversion_helper(val, conversion): """Apply conversion to val. Recursively apply conversion if `val` #is a nested tuple/list structure.""" if not isinstance(val, (tuple, list)): return conversion(val) rtn = [conversion_helper(v, conversion) for v in val] if isinstance(val, tuple): ...
4381a4ac0f1d3e32cf22abd41ae224252fbe40fc
73,216
def fibonaccinumber(n): """ >>fibonaccinumber(6) 1 1 2 3 5 8 >>fibonaccinumber(10) 1 1 2 3 5 8 13 21 34 55 """ if n<0: print("Incorrect input") elif n==0: return 0 elif n==1: return 1 else: n1 , n2 =1,1 count = 1 w...
c69d23d2603360cba6b5d5e600da1aa96dcfec60
73,217
import numpy import copy def get_uniform_colours_in_hsv_space( num_colours, colour_to_exclude_rgb=None, min_rgb_distance_from_colour=DEFAULT_MIN_RGB_DISTANCE): """Returns array of uniformly spaced colours in HSV space. N = number of colours :param num_colours: Number of colours. :par...
13a9995868a552411e3c255a6c3c2d1ecdaeaece
73,218
def obtain_centroid(X_train, clustering_algorithm, categorical_cols, sc, n_clusters): """ Function to obtain the centroid of a group of data points. It uses K-Prototypes or with K-Modes algorithm. It returns the centroid/prototype point for that data as well as the assigned clusters for each d...
41809d604d593640ba0ba4a24ab54c4bd1e1ecc6
73,219
def play(pet) -> bool: """Return False if any of the stats is 0.""" if (not pet.hunger) or (not pet.thirst) or (not pet.energy) or (not pet.fitness) or (not pet.mental_health): print("Oh no! Take better care of", pet.name, "next time!") print("Thank you for playing!") print(" - - - ") ...
482b38868d402d40687ed0c7495a122c50783fe3
73,220
def expand_composites (properties): """ Expand all composite properties in the set so that all components are explicitly expressed. """ explicit_features = get_grist (properties) result = [] # now expand composite features for p in properties: expanded = expand_composite (p) ...
01ad6406277a163349390e8c8f3260b1363c6395
73,221
def all(): """all() -> [ all toolbars ]""" return _toolbars.values()
216ebc5a20e9326ce08bf2422593471daf92b118
73,222
def base_prob(phred_score): """ Returns the probabilty that a base is incorrect, given its Phred score. """ prob = 10.0**(-float(phred_score)/10) return prob
8231019213204e65d577ea86d1e2e0e7352a3f70
73,223
def create_hostname_from_ip(mgmt_ip, country_code): """ example country code: CH, UK creates the switch hostname based on the mgmt IP and the country code """ try: temp_ip_split = mgmt_ip.split(".") hostname = \ f"SWI{country_code}{temp_ip_split[1].zfill(3)}{temp_ip_split...
a1b366a5b03f36f48e832e53f772482d5967b106
73,225
import re def need_format(line: str) -> bool: """ Return true if line as a title declaration followed by content """ return ( ( re.search("\t+e_\w*[-'\w]*\W*=", line) is not None and re.search("\t+e_\w*[-'\w]*\W*=\W*{[\w\t]*\n", line) is None and re.search("...
61576aa02a745db8b0ce0c9c4c9a4d4589e8d842
73,227
def radec_to_eci(ra, dec): """ Convert from RA,Dec to ECI. The input ``ra`` and ``dec`` values can be 1-d arrays of length N in which case the output ``ECI`` will be an array with shape (N, 3). The N dimension can actually be any multidimensional shape. :param ra: Right Ascension (degrees) :pa...
c967443c057a426b9317fda992157e00a7b9f219
73,228
import re def format_float(value, width=np.get_printoptions()['precision']): """Return a float value with the specified width. This function results in a more compact scientific notation where relevant. """ text = "{:.{width}g}".format(value, width=width) return re.sub(r"e(-?)0*(\d+)", r"e\1\...
36da161711ce435303dd35350d38c40627ac3740
73,230
from typing import Union def is_bool(value: Union[str, bool]) -> bool: """validate whether the value is boolean""" return (value in true_list + false_list) or (isinstance(value, bool))
92b7c34278a1df7be4a095201e1e565d2dd664da
73,231
import functools def creator_only_query(func): """ If given user is not a creator, restrict access. """ @functools.wraps(func) def wrapper(update: Update, context: CallbackContext): query = update.callback_query if not is_creator(context.bot, update.effective_chat.id, query.from_u...
4a7e9fa4850798362c4614450f85ba4586ed9a3b
73,232
import logging def if_action(hass, config): """ Wraps action method with state based condition. """ entity_id = config.get(CONF_ENTITY_ID) state = config.get(CONF_STATE) if entity_id is None or state is None: logging.getLogger(__name__).error( "Missing if-condition configuration k...
ad39b6143f7ac0a40db21ff14005a93116230241
73,233
def builderFor(action, hypervisor=None, template=None, service=None): """ This decorator is used to supply metadata for functions which is then used to find suitable methods during building just by these properties. :param action: Name of the generic step/action (see planner) that this function impleme...
1dddfd8dc5dbc87e5a018fc4fb144bef8a8f98e3
73,234
from typing import Dict from typing import List from typing import Union from pathlib import Path import json def compile_standard( input_data: Dict, base_path: str = None, allow_paths: List = None, output_dir: str = None, overwrite: bool = False, solc_binary: Union[str, Path] = None, solc...
8f50e7fe42a54d1005469128632e3a374aeccf76
73,235
def undeployed_value_only_calculator(repository, undeployed_value_tuple, deployed_value_tuple): """ Just return the undeployed value as the value. This calculator can be used when there will be no deployed value. """ return undeployed_value_tuple[2]
58294274d37b4c7bb9cad21bb01260986cb0d6ae
73,236
import re def _remove_inner_punctuation(string): """ If two strings are separated by & or -, remove the symbol and join the strings. Example ------- >>> _remove_inner_punctuation("This is AT&T here") 'This is ATT here' >>> _remove_inner_punctuation("A T & T") 'A T T' """ ...
4ca3e7f91e35dba2e0a34f1dfd935e004623875e
73,238
def makeLighter(color: colors.Color) -> colors.Color: """ Takes a color and returns a slightly lighter version of the original color. :param Color color: the color you want to lighten :return: the new, lighter color :rtype: Color :raises TypeError: if ``color`` is not a :py:class:`~.colors....
8b715ff6da82378e8c2078ddf9cd0bfd483c39a4
73,239
def _get_pgpass(params): """Find a password for the given connection parameters. The params parameter MUST be a dict!""" def _matchparam(name, value, defval=""): """Match .pgpass parameter with a value.""" if value == '*': return True else: return value == s...
67ea73722be8b5843da1f1edbf80ad796b4279a3
73,240
def tsdf_via_vox(depth, scene_info, vox_map, is_flipped): """ Convert a vox into tsdf format :param depth: the depth info :param scene_info: the scene info, including voxel resolution and image viewpoint :param vox_map: the non-empty voxel :param is_flipped: whether to use the flipped signal ...
ae960bcb7238a342b4ed46ef692cbd4cd028d7e0
73,242
def _scrape_main_synonym_section(left_content): """Scrapes the main/default synonym section for a word. If there is no pos listed, use the one listed for the word """ synonym_header = left_content.find('div', {'class' : 'synonyms_list'}) synonym_labels = synony...
21063c652e733e6e6f6ca32bdf0d343bdbbb80f4
73,243
def get_cluster(*, cluster_name: str, region: str, vpc_id: str) -> EC2Cluster: """ Get an existing EC2 cluster. """ cluster = get_clusters( cluster_names=[cluster_name], region=region, vpc_id=vpc_id) return cluster[0]
79d7bdabc8ce265febe18b99ad7f1154af275ffb
73,244
import typing def lydia_fail() -> typing.RouteReturn: """Route the user is sent back by Lydia after cancelling payment.""" flask.flash(_("Paiement annulé"), "danger") return utils.ensure_safe_redirect("payments.pay", next=None)
552e04bf8c324d2ea292eb2664a5706cad3e30e3
73,246
def function(*args, **kwargs): """Wrapper for tf.function with TF Agents-specific customizations. Example: ```python @common.function() def my_eager_code(x, y): ... ``` Args: *args: Args for tf.function. **kwargs: Keyword args for tf.function. Returns: A tf.function wrapper. """ ...
bbc12b679353b006fabbfaf69b030c90921602fa
73,247
import zipfile def get_templates(templates_zip_archive): """ Unzip the Summary File Templates archive file; generate and return a dictionary mapping 'geo' and seq # to corresponding file column name lists. """ templates = dict() with zipfile.ZipFile(templates_zip_archive) as z: # L...
c3861389577d230983ea78e6d1e7ddc809da8031
73,248
def get_candidate_objects(output, img_size, classes, anchors=None): """ convert network output to bounding box predictions """ threshold = 0.2 iou_threshold = 0.4 boxes, probs = parse_yolo_output(output, img_size, len(classes), anchors) filter_mat_probs = (probs >= threshold) filter_mat_boxes ...
66aeae6db2fbd57155731e0c1d6443eb447ae079
73,249
import re def generateHashtags(randomTests): """Generates a hashtag from a level 1+ category name using Regular Expressions and other rules. Arguments: randomTests {Dictionary} -- A test category and hashtag (level 1+) categories Returns: Dictionary -- The input dictionary with added has...
96478924f04706b88cb367d5aca334225771788b
73,250
def check_url(url): """Checks whether `url` is a valid URL. """ parsed = urlparse(url) return bool(parsed.netloc) and bool(parsed.scheme)
17c8f546df43f107f84a855f78abcfc2c008d38f
73,251
def _cache_getter(key): """ Generates a function that will get the cached data of a key """ def f(): data = memcache.get(key) if data == none_sentinel_string: return None return data return f
9acf6c4b412bbcad0b08d381326480a3ed2178d6
73,252
def synthetic_data(w, b, num_examples): """生成 y = Xw + b + 噪声。""" X = flow.randn(num_examples, w.shape[0]) y = flow.matmul(X, w.reshape(w.shape[0], -1)) + b y = y.reshape(-1) y += flow.tensor(np.random.normal(0, 0.01, y.shape[0]).astype(np.float32)) return X, flow.reshape(y, (-1, 1))
5e3e69c7c23843c0c4b232dcd157d0c2c3b6f72e
73,253
def NewCMessage(full_message_name): """Creates a new C++ protocol message by its name.""" return _net_proto2___python.NewCMessage(full_message_name)
2456c6cdd604660c8a0ea36e4988a2bb5ed2acdd
73,254
def get_description(khoros_object, identifier=None, category_details=None): """This function retrieves the description for a given category. .. versionadded:: 2.1.0 :param khoros_object: The core :py:class:`khoros.Khoros` object :type khoros_object: class[khoros.Khoros] :param identifier: The Cate...
b0b28c60fc133ca0982ee63cfd2da55f199375bf
73,255
def get_longest_element(focus): """ cycles thru the status_results dictionary in the indicated key or field list and finds the longest piece of text in it :param focus: the key or field in value list that is being searched for longest value :return: the longest value """ return (len(max(focu...
d00c02d3d02ebd371f16ef16fd2e7daa0ead47ac
73,256
from pathlib import Path def get_facemap_root_data_dir() -> list: """ It is recommended that all paths in DataJoint Elements stored as relative paths, with respect to some user-configured "root" director(y/ies). The root(s) may vary between data modalities and user machines get_fm_root_data_dir() ...
c02903b9828495e1d5533e91367ddbc7ec14f656
73,257
import torch def caption_image_beam_search(encoder, decoder, image_path, word_map, beam_size): """ Reads an image and captions it with beam search. :param encoder: encoder model :param decoder: decoder model :param image_path: path to image :param word_map: word map :param beam_size: numb...
2f08ac5289714c4de51a6ff5a4031bf29a9d4d98
73,258
def _NodeConfigResolver(single_node_fn, all_nodes_fn, node_uuids, opts): """Calculate node addresses using configuration. Note that strings in node_uuids are treated as node names if the UUID is not found in the configuration. """ accept_offline_node = (opts is rpc_defs.ACCEPT_OFFLINE_NODE) assert accept...
925931bc0f80b8af48c7d7e5a5bd52587378d103
73,259
def get_num_classes(labels): """Get total number of classes. Arguments: labels {list} -- label values. """ num_classes = max(labels) + 1 missing_classes = [] for l in range(num_classes): if l not in labels: missing_classes.append(l) if len(missing_classes): ...
4573bbf81fab0396454167287e86492e0ee7cd48
73,260
def detail_url(address_id): """Return the detail url for user address""" return reverse('user:address-detail', args=[address_id])
047d96aa4f878021ad912bce91b33f5fe1a3acff
73,261
def get_empty_concat_loss(sentence, inv): """Returns list of empty concatenation loss matrices.""" empty_concat_loss = [] for i in range(1, len(sentence)): prev_diphone = sentence[i - 1] this_diphone = sentence[i] loss_mat = np.zeros((len(inv[prev_diphone]), len(inv[this_diphone]))) ...
7f86ff28a63a5ed6cb3ca933c26db1dc51553b04
73,262
from typing import List def existing_ids() -> List[str]: """ Return a list of existing post ids so that we don't send duplicate notifications for posts the user has already seen. """ existing_ids = CURSOR.execute( f""" SELECT id FROM posts; """ ).fetchall() # Unpack th...
fd810b3e104408be038089b0da4d9c5ff17da53b
73,263
from typing import List def context_table_to_dicts(table: Table, orient='index', use_nan=True) -> List[dict]: """ Converts a context table in a feature file into a list of dictionaries :param use_nan: :param table: The context.table from a scenario :param orient: orient for df to_dict ...
4a535a6ee20eefd971a67257b106edd969ee7100
73,264
def store_edges(edge_data): """Store edges in a dict where the keys are the edge times""" time_edge_map = {} for i in range(len(edge_data)): current_time = edge_data[i,0] if not current_time in time_edge_map: time_edge_map[current_time] = [] time_edge_map[current_time].ap...
885bb4f4e6480904a09bb7afe7d85053643a3f1a
73,265
def group_list(auth=None, **kwargs): """ List groups CLI Example: .. code-block:: bash salt '*' keystoneng.group_list salt '*' keystoneng.group_list domain_id=b62e76fbeeff4e8fb77073f591cf211e """ cloud = get_operator_cloud(auth) kwargs = _clean_kwargs(**kwargs) return ...
bfdb1563fcc843e0db577888a866d3dcbd044132
73,266
def get_yaml_basepath(): """Returns the full path of the directory in which builtins are located.""" if _handler_dir is None: set_builtins_dir(DEFAULT_DIR) return _handler_dir
4b824c8bb040aea3db085c85adbbbe715df12c19
73,267
def filter_linker_flavour(args): """Remove `-flavor gnu`.""" new_args = [] ignore = False for arg in args: if ignore: ignore = False # ignore this argument else: if arg == '-flavor': ignore = True else: new_args.append(a...
f37aac3c7b14f25350c945c5258d851402292330
73,268
def str_sha1(str): """Calculates the SHA1 hex digest of a unicode string.""" return bytes_sha1(bytes(str, encoding='latin1', errors='replace'))
dc986b4129f082458321f0e614df87751648a2df
73,269
import csv def convert_connections_csv_to_list_of_dics(connectionsDB): """ """ connections_list_of_dics=[] with open(connectionsDB, 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"',skipinitialspace=True) for row in reader: this_line_dic={} # print(row) # p...
5cdc1d40878ec2d3eb4ff8128102713cd5d76602
73,270
from enum import Enum from typing import List def declare(*, group: Enum, version: int, event_types: List[int]) -> callable: """ Declare class builder for a particular MOF group version and event types :param group: Event trace group :param version: version of mof class :param event_types: list of...
f1aa9421f4a12efa5d34ae7d04b85fd2a2347a9f
73,271
from unittest.mock import Mock import requests def timeout_se(*args, **kwargs): """A function to mock requests timeouts over multiple responses. You must set REQUEST_COUNT global variable to 0 and TIMEOUTS global variable to desired number before this function is be called. Returns: Mock: A ...
f1abea240335301ebb059dc07e180f289cf65fbe
73,272
def get_argument(arguments, index=None, key=None): """ Return the indicated argument. If `arguments` is a collection, then the indicated argument value is looked up by index or key (depending on the collection). If `arguments` is just a single, atomic value, then that value is returned. Other...
3d0a0932cf4ca7fc2de5e233dbf4cc890a4422b4
73,273
def norm_p(z): """ Caclulate (approx) the p-value for a standard normal distribution Parameters: z (ee.Image): image containing z-scores Returns: ee.Image: image containing p-values """ return ee.Image.constant(1).subtract(z.multiply(-1.65451).exp().add(1).pow(-1))
2d066983daa6eee5d2b7a1fa0235399e37f31a26
73,274
import random def random_string(length, charset): """ Return a random string of the given length from the given character set. :param int length: The length of string to return :param str charset: A string of characters to choose from :returns: A random string :rtype: str """ n = ...
1370f86a2e696ba6030b719ec8e32631f1865e01
73,275
import requests import json def infer_batch(seqs, host, model, ver=None): """Returns 3d then 8d None goes to default url This url : 'http://131.215.2.28:8501/v1/models/dspace_embed/versions/6:predict' host = '131.215.2.28:8501' ver = 6 model = 'models/dspace_embed' """ seq_arr = pre...
94e8239d12a1bef852d19c7d390ea3709eaf9c26
73,276
def preproccessing(locator, total_demand, buildings_heating_demand, buildings_cooling_demand, weather_file, district_heating_network, district_cooling_network): """ This function aims at preprocessing all data for the optimization. :param locator: path to locator function :param tota...
76beb45f02013de20c48518d82cbda2a76308ac1
73,278
def XYZ_to_sd_Jakob2019( XYZ, cmfs=STANDARD_OBSERVER_CMFS['CIE 1931 2 Degree Standard Observer'] .copy().align(DEFAULT_SPECTRAL_SHAPE_JAKOB_2019), illuminant=sd_ones(DEFAULT_SPECTRAL_SHAPE_JAKOB_2019), optimisation_kwargs=None, additional_data=False): """ Recovers...
d7c4a1fda23fc659cce6e004610ddaa96580e7a7
73,281
def primepi(n): """ Return the value of the prime counting function pi(n) = the number of prime numbers less than or equal to n. The number n need not necessarily be an integer. Examples ======== >>> from sympy import primepi >>> primepi(25) 9 See A...
90534c01bbaa600ff9689110911e01fc43f1ac8a
73,282
def delete_item(category_name, item_id): """ Performs the actual item delete """ user = get_user(login_session['email']) item = session.query(Item).filter_by(id=item_id).one() if item.user_id != user.id: flash("You cannot delete other users' items") return redirect(url_for('show_...
7b073d0a1a61c8619683f8761a74a3cab89b3947
73,283
def get_variables(x): """ Gets all variables in a formula. """ v = {} VariablesVisitor(v)(x) return [val for _, val in sorted(v.items(), key=lambda x: x[0])]
f2a62951f4feb2c8061f775e7482e3b2ebb933ea
73,284
def scalar(dtype=dtypes.float32): """ Convenience function that defines a scalar (array of size 1). """ return ndarray([1], dtype)
3a20d5cf141b8f26bf21f84a9abd724caf5dac94
73,285
def fill_sym_mat(mat): """Make a upper diagonal or lower diagonal matrix symmetric Parameters ---------- mat : 2d array the matrix we want symmetric """ return mat + mat.T - np.diag(mat.diagonal())
3c1d536f585e787b27c74255afb11d1bfe09fd05
73,287
def psql_settings_from_config(config, section_name): """ load psql connection settings from config object """ conf = config[section_name] psql = SectionKey(section_name) return PsqlSettings(host=conf[psql.key('host')].strip(), port=conf[psql.key('port')].strip(), ...
f7eede68c9a370d4ca852d6f4896d51f933eedae
73,288
def get_workspace_dir(): """Returns the workspace directory to use for tiflash. Returns: str: workspace to use for tiflash (fullpath) """ # Uses user's home directory workspace = DEFAULT_WORKSPACE return workspace
14c83f40dc508d93209877ba28b72826c0efbdf3
73,289
def xlate(vname): """Translate""" if vname in ["ws_10m_nw", "ws_40m_nw", "ws_120m_nw"]: return vname + "ht" return vname
8759031dcc47f5b34128f6b621f837e92e6c9b23
73,290
def reverse_spline(tck): """Reverse the direction of a spline (parametric or nonparametric), without changing the range of the t (parametric) or x (nonparametric) values.""" t, c, k = tck rt = t[-1] - t[::-1] rc = c[::-1] return rt, rc, k
77c239fa8360657ed4ad4c1eb8d18493c97a84a1
73,291
import inspect def is_param_method(obj, has_deps=False): """Whether the object is a method on a parameterized object. Args: obj: Object to check has_deps (boolean, optional): Check for dependencies Whether to also check whether the method has been annotated with param.depend...
55896f9e2e6f58ef12ec4f83ece318e797c4f7eb
73,292
import importlib import pkgutil def list_submodules(package, recursive=True): """ Recursively (optional) find the submodules from a module or directory Args: package (str or module): Root module or directory to load submodules from recursive (bool, optional): Recursively find. Defaults to...
a5d69affc4cd19bd3e7c67c2d006c224bbafe80d
73,293
def trainee_already_marked_training_date(trainee, training_date): """Check whether trainee already marked the given training date. If trainee already has training day info it means he/she answered marked the given date. Args: trainee(models.Trainee): trainee instance to check whether already marke...
138006be069201923017e0277ffec6a7c06080b4
73,294
def permission_list(): """权限列表""" if request.method == 'GET': permissions = Permission.query.all() return render_template('permissions.html', permissions=permissions)
94128ed17bb3806ffcbc09779ca7b2aac1530d5e
73,296
def serving_input_receiver_fn(): """ Build serving inputs """ input_ids = tf.placeholder(dtype= tf.int32, shape=[None, 128], name='input_ids') input_mask = tf.placeholder(dtype= tf.int32, shape=[None, 128], name='input_mask') segment_ids = tf.placeholder(dtype= tf.int32, shape=[None, 128], name=...
6d4dc551f446d49a695e46dd9909c17ba6a793de
73,298
import collections def _load_features(root): """Returns {name: Feature}""" out = collections.OrderedDict() for elem in root.findall('feature'): name = elem.attrib['name'] api = elem.attrib['api'] number = tuple([int(x) for x in elem.attrib['number'].split('.')]) requires = ...
37bc0e9c6c0d827f020a6667679936274b5f87e0
73,299
def vmag(v: list[float]) -> float: """Compute the Magnitude or length of a vector v of arbitrary dimension n equal to len(v) Args: v: list of ints or floats Returns: float """ s = sum(i * i for i in v) return sqrt(s)
c83b8e06c2a3a5efdb07b8d15d06bd52e853556d
73,300
def multi_win_eliminate(func, data, numwin=1, **kwargs): """Convert single winner method to multi-winner method, using candidate elimination.""" winners = [] num_left = numwin data = data.copy() outputs = [] ties = [] while num_left > 0: winners_ii, ties_ii, out...
cc3d7eec890058a1ef7d34615f4765ea89c5a058
73,301
def number_components(root, vertex_status): """ Number the components to the right of SOURCE vertex in the forest input to the assembly phase INPUT: - ``root`` -- the forest which contains the components and cocomponents - ``vertex_status`` -- dictionary which stores the position of vertex ...
38282f305bec3eb3e28a4132ad0c094ea98f5d0d
73,302
def compute_score_of_segmentation(reference, segments_in_time, window_length = 0.5): """ Computes precision, recall and f measure from estimated segments and the reference, both in seconds. Scores are computed from the mir_eval toolbox. Parameters ---------- reference : list of tuples ...
2227d1d8d6e120bca1a54d0a204847406db73296
73,304
def get_countries(): """ The endpoint is for now publicly available. Returns: JSON of all countries. """ countries = Country.query # no need to order countries_data = [country.to_dict() for country in countries.all()] return jsonify(countries=countries_data)
2a1a9aeac95a6cd768534603ac7643cea06c02bc
73,305
def calc_reference_target(*args): """calc_reference_target(ea_t from, refinfo_t ri, adiff_t opval) -> ea_t""" return _idaapi.calc_reference_target(*args)
967af2f9f1851dffe132d427caefbedaa1f545c7
73,306
from typing import Any import numbers def _is_metric_diffable(metric_value: Any): """Check whether a metric value is a number or an ndarray of numbers.""" return (isinstance(metric_value, numbers.Number) or (isinstance(metric_value, np.ndarray) and np.issubdtype(metric_value.dtype, np.number)...
d5ce9122324c7902865ee6d5c3e70a00c462c568
73,307
def add_one(x: int) -> int: """ Returns input value added one :param x: value greater than or equal to 0 :return: x + 1 :except x less than 0: """ assert x >= 0 return x + 1
eaf60652a9dc210b3f4174c18873be1973c4f99e
73,308
def svn_fs_get_uuid(*args): """svn_fs_get_uuid(svn_fs_t * fs, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_get_uuid(*args)
d3d0316a8abb622a07ae69137376fc804bce9f6a
73,311
def listify(iterable): """Returns a flattened list of iterable if not already a list Parameters ---------- iterable : iter-like An iterable object that will be wrapped within a list Returns ------- list An enclosing 1-D list of iterable if not already a list """ a...
845428c8a7d4d431fd2fb94e338b004a5ac06ceb
73,312
async def text_to_pic(text: str, css_path: str = None, width: int = 500) -> bytes: """多行文本转图片 Args: text (str): 纯文本, 可多行 css_path (str, optional): css文件 width (int, optional): 图片宽度,默认为 500 Returns: bytes: 图片, 可直接发送 """ template = env.get_template("text.html") r...
9af7b461af684b9f71d14edf39be3bb0cd770215
73,313
def LU_nopivotv(A): """ % Fattorizzazione PA=LU senza pivot versione vettorizzata intermedia In output: L matrice triangolare inferiore U matrice triangolare superiore P matrice identità tali che LU=PA=A """ # Test dimensione m,n=A.shape flag=0; if n!=m: prin...
4ae8a22f9790c6433e2263d237696e66b4b25678
73,314
def r2_metric(y_true, y_pred): """ Compute r2 metric. Args: y_true (tf.tensor): True y-values. y_pred (tf.tensor): Predicted y-values. Returns: tf.tensor: r2 metric. """ SS_res = ks.backend.sum(ks.backend.square(y_true - y_pred)) SS_tot = ks.backend.sum(ks.backen...
2b3e4e26a7eedf67722667727ec198c5ef211240
73,316
from typing import List from typing import Callable def post(route: str, additional_methods: List[str]=[]) -> Callable: """ States that a function will be executed when a POST request is sent to the server. """ return lambda func: (route, 'POST', func, additional_methods)
e162eb98ae612081a1eb54229b965deb7457c62f
73,317
def get_K(M, R, xi, theta, dthetaXdxi, xi1, dthetaXdxi1, n): """ The proportionality constant for the polytropic equation of state Positional Arguments: M -> Stellar Mass in g R -> Stellar Radius in cm xi -> dimensionless radius theta -> solution to theta from integration ...
67dd9c8bc8e79b1d45d2fda5053b150ae46e80e4
73,318
def FileClassify(diri, log): """ Classifies all files in a directory and writes a night log of science images """ # define output lists sim_sci = [] flats = [] ThAr_ref = [] ThAr_ref_dates = [] flat_ref_dates = [] obnames = [] exptimes ...
d812785fb8476243fa9cdff014acc8ec14c5bec1
73,319
import json def read_config(path_to_config): """Parses and returns configuration from чfile.""" data = json.load(open(path_to_config)) deploy = data['deploy']['monique'] queue_host = deploy['queue_host'] queue_port = deploy['queue_port'] return JobcontrolConfig(queue_host, queue_port)
db94cc797743775d80bf2fa47289db0e6321a096
73,320
def open_rmf_file_read_only(*args): """open_rmf_file_read_only(std::string path) -> FileConstHandle""" return _RMF.open_rmf_file_read_only(*args)
ea6c3054cc1061c1cf741f0fcd98be5f385869bd
73,321
import numpy def launch(cfg): """ Runs a GPATH job Parameters ---------- cfg : gpath.parse.Settings Parsed YAML dict with attribute-like access """ gpath.plugin.import_plugins(*cfg.genes) gpath.plugin.import_plugins(*cfg.objectives) import_module(cfg.similarity.module.rspl...
fd26c42ec926645f427e24620fa3c0b487d35a4b
73,323
def compile_extra(typingctx, targetctx, func, args, return_type, flags, locals, library=None, pipeline_class=Compiler): """Compiler entry point Parameter --------- typingctx : typing context targetctx : target context func : function the python function...
c0a8e7335b3ca6a8fe70c52cd841a7f1947e1ee8
73,324
def run_dark_zone(B_cells, cycle_number, nb_rounds = 2): """ B cells proliferate and undergo SHM in the dark zone. """ for i in range(nb_rounds): ftrack2.write('division/mutation round = %d' %(i+1)) ftrack2.write('\n') ftrack2.flush() new_cells = [] for b in B_cells:...
5eab738d9e0a5c5e69a5e639bfd877bd0be89b20
73,326
import itertools def rvps_from_bed(file_path, chrom_col = 0, region_cols = (1,2), value_col = None, ID_col = None, value_fill = 1, header = None, allowed_chroms = None, sep =...
8500fd6e77b0537852d1d351babebf3404e5a113
73,327
def select_imregions(ptype, full_im1, full_im2, overlap_pixels): """Select image regions to extract keypoints from.""" if ptype == 'z': im1 = full_im1 im2 = full_im2 elif ptype in 'y': y1 = full_im1.shape[0] - overlap_pixels[0] y2 = overlap_pixels[0] im1 = full_im1[y...
5c4b3caae4216bd84ad975603e8196c6061ce007
73,328
def plume_model_demo(dt=0.01, t_max=100, steps_per_frame=200, seed=DEFAULT_SEED): """Set up plume model and animate puffs overlayed over velocity field. Puff positions displayed using Matplotlib `scatter` plot function and velocity field displayed using `quiver` plot function. plot...
56d21108d5795674e8fa19719540b99255c61c74
73,329
def edit(*args, **kwargs): """ Checks out a file for editing. All file paths should be supplied as arguments! :rtype: dict """ # Create repository # p4 = createAdapter(**kwargs) try: # Check out files # p4.connect() results = p4.run('edit', '-c', k...
40fe17e8f7f9464b01b123c6323deadebbc425a5
73,330
import time def pytest_runtest_protocol(item, nextitem): """ Run the test protocol. Note: when teardown fails, two reports are generated for the case, one for the test case and the other for the teardown error. """ reruns = get_reruns_count(item) if reruns is None: # global settin...
ea0dd5408aec89c07be13123c62a7d6521cf9f92
73,331
from typing import Iterable from re import T def uniq(iterable: Iterable[T]) -> Iterable[T]: """Imitate the Unix tool uniq, dedup adjacent items This function guarantees overall uniqueness of its elements if and only if the iterable argument is sorted first. """ return map(itemgetter(0), groupby...
d0a370caa3b4067da37e2a7348fb672315c76f1e
73,332
def pitch(ra, dec, time): """Calculate sun pitch angle for the given spacecraft attitude ``ra``, ``dec`` at ``time``. Example:: >>> Ska.Sun.pitch(10., 20., '2009:001:00:01:02') 96.256434327840864 :param ra: right ascension :param dec: declination :param time: time (any Chandra.Time ...
52f07cd9b26493f408621795f5d8f171ba178787
73,333