content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def __unzip_labels(label): """unzips a string with more than one word Parameters ---------- label : tuple tuple or list of the text labels from the folder name Returns ------- list splited labels as list of strings """ labels = re.split('(?=[A-Z])', labe...
c442eaadf18c51fdb7d9519bc00658b97657a225
20,754
def check_user(user, event): """ Checks whether the ``ReactionAddEvent``, ``ReactionDeleteEvent``'s user is same as the given one. Parameters ---------- user : ``ClientUserBase`` The user who should be matched. event : ``ReactionAddEvent``, ``ReactionDeleteEvent`` The reacti...
37c5e280ced5a3470ac9691e6cb0dcadf3e3c550
20,756
def is_theme(labels, zen_issue): """Check If Issue Is a Release Theme. Use the input Github Issue object and Zenhub Issue object to check: * if issue is an Epic (Zenhub) * if issue contains a `theme` label """ if zen_issue['is_epic']: if 'theme' in labels: return True
380dbe8d4c9105a49a8ae211f55dcbfd35c38d3c
20,775
from typing import Dict from typing import Any import pprint def describe_item(data: Dict[str, Any], name: str) -> str: """ Function that takes in a data set (e.g. CREATURES, EQUIPMENT, etc.) and the name of an item in that data set and returns detailed information about that item in the form of a str...
4df9e99f713effc00714342f54e2bd135b580675
20,777
def mini(a,b): """ Minimal value >>> mini(3,4) 3 """ if a < b: return a return b
2d49ce51bd239dd5ceb57396d7ed107f1309c203
20,778
def prod(iterable): """Computes the product of all items in iterable.""" prod = 1 for item in iterable: prod *= item return prod
f5ddea44c14a6d1dc77a3049723609358c1e8525
20,781
def areinstance(tokens, classes): """ >>> tokens = (TimeToken(15), TimeToken(16)) >>> areinstance(tokens, TimeToken) True >>> tokens = (TimeToken(15), DayToken(7, 5, 2018)) >>> areinstance(tokens, TimeToken) False >>> areinstance(tokens, (TimeToken, DayToken)) True """ assert...
27cf41a668dfcd52975becd0ae96c81d2c9ab385
20,782
def do_decomposition(gene_trail, selection): """Given a list of lists gene_trail and indexes for every item to be selected in every list in gene_trail, returns a list representing the corresponding decomposition. For example, if gene_trail is [['a', 'b'], ['c'], ['d','e']] and the index for the fir...
cbe3a942db5fb447f9e7ffe8f0866419b04f81f1
20,784
def processEnum(enum, tableExists=True, join=True): """ Take an Enum object generated by the PyDBML library and use it to generate SQLite DDL for creating an enum table for "full" enum emulation mode only. Parameters: enum (Enum): Enum object generated by PyDBML library representing an SQL enum....
832ca77c1287790ea33b26baacdeee5b3f611785
20,785
from typing import OrderedDict def _get_file_metadata(help_topic_dict): """ Parse a dictionary of help topics from the help index and return back an ordered dictionary associating help file names with their titles. Assumes the help dictionary has already been validated. """ retVal = OrderedDi...
6e03564f28ebc9ab8dc8ce12d314d18c35cf3518
20,786
def is_no_overlap(*set_list): """ Test if there's no common item in several set. """ return sum([len(s) for s in set_list]) == len(set.union(*[set(s) for s in set_list]))
300253d499c22bb398837c9766a9f5d8f7b5c720
20,790
from warnings import warn def _format_1(raw): """ Format data with protocol 1. :param raw: returned by _load_raw :return: formatted data """ data, metadata = raw[0]['data'], raw[0]['metadata'] # Check for more content if len(raw) > 1: base_key = 'extra' key = base_key...
0939ffb4242828a7857f0f145e4adeb90ec6cff1
20,791
def first(iterable): """ Gets the first element from an iterable. If there are no items or there are not enough items, then None will be returned. :param iterable: Iterable :return: First element from the iterable """ if iterable is None or len(iterable) == 0: return None return ...
246ca69493a601343e1b1da201c68e2d8a3adc55
20,794
import re def allsplitext(path): """Split all the pathname extensions, so that "a/b.c.d" -> "a/b", ".c.d" """ match = re.search(r'((.*/)*[^.]*)([^/]*)',path) if not match: return path,"" else: return match.group(1),match.group(3)
06baf4d1a58c9f550bd2351171db57a8fc7620d2
20,796
def is_prepositional_tag(nltk_pos_tag): """ Returns True iff the given nltk tag is a preposition """ return nltk_pos_tag == "IN"
746a1439613a2203e6247924fe480792e171eb7b
20,798
import re def clean_data(d): """Replace newline, tab, and whitespace with single space.""" return re.sub("\s{2}", " ", re.sub(r"(\t|\n|\s)+", " ", d.strip()))
3c6b9032588d0cb2ca359ff27d727ade7011048a
20,801
def calc_alpha_init(alpha, decay): """ Calculate the numerator such that at t=0, a/(decay+t)=alpha """ if not decay or decay <= 0: return alpha else: return float(alpha * decay)
41725753868a01b89f0a1ba0bc0b37b0ac2499c2
20,807
def tuple_to_list(t): """ Convert a markup tuple: (text,[(color,pos),...]) To a markup list: [(color,textpart),...] This is the opposite to urwid.util.decompose_tagmarkup """ (text,attrs) = t pc = 0 l = [] for (attr,pos) in attrs: if attr == None: l.append(text[pc:pc+pos]) else: l.append((at...
466767cd7d1d43665141908661ca75b291b4db50
20,811
from typing import Iterable from typing import Tuple import networkx def build_graph(data: Iterable[Tuple[dict, str, dict]]): """ Builds a NetworkX DiGraph object from (Child, Edge, Parent) triples. Each triple is represented as a directed edge from Child to Parent in the DiGraph. Child and Paren...
6d43f3d2b9698eaac54cfcee38fd005e6762eaf6
20,813
def find_first_feature(tree): """Finds the first feature in a tree, we then use this in the split condition It doesn't matter which feature we use, as both of the leaves will add the same value Parameters ---------- tree : dict parsed model """ if 'split' in t...
d57d29c3aadb0269d39fa73d27cd56416cc3e456
20,819
def sum_product(array: list) -> dict: """ BIG-O Notation: This will take O(N) time. The fact that we iterate through the array twice doesn't matter. :param array: list of numbers :return: """ total_sum = 0 total_product = 1 for i in array: total_sum += i for i in array: ...
53a8ac6000f9c6f722ef7159e31d1dc5f069fa9b
20,821
from pathlib import Path def get_file_extension(filepath: str) -> str: """ Returns the extension for a given filepath Examples: get_file_extension("myfile.txt") == "txt" get_file_extension("myfile.tar.gz") == "tar.gz" get_file_extension("myfile") == "" """ extension_with_d...
d90dd071298c1ee429d913abd831030a60086b1b
20,826
def unescape(s): """The inverse of cgi.escape().""" s = s.replace('&quot;', '"').replace('&gt;', '>').replace('&lt;', '<') return s.replace('&amp;', '&')
3bad6bc3679405dd0d223ea8ab6362a996067ea5
20,827
import random def seq_permutation(seq: str, k: int = 1) -> str: """Shuffle a genomic sequence Args: seq (str): Sequence to be shuffled. k (int): For `k==1`, we shuffle individual characters. For `k>1`, we shuffle k-mers. Returns: Shuffled sequence. """ if k == 1: ...
a789c2a5cb00e2e5fd140ba889510e6b7fd556d3
20,832
import math def get_normalized_meter_value(t): """ Expects a value between 0 and 1 (0 -> 00:00:00 || 1 -> 24:00:00) and returns the normalized simulated household consumption at that time, according to this Graph: http://blog.abodit.com/images/uploads/2010/05/HomeEnergyConsumption.png The formula...
03f40967f05de4d23d7600286bfc2927fea544d6
20,835
def squared_dist(x1, x2): """Computes squared Euclidean distance between coordinate x1 and coordinate x2""" return sum([(i1 - i2)**2 for i1, i2 in zip(x1, x2)])
c4ae86e54eb1630c20546a5f0563d9db24eebd3a
20,838
def itensity_rescaling_one_volume(volume): """ Rescaling the itensity of an nd volume based on max and min value inputs: volume: the input nd volume outputs: out: the normalized nd volume """ out = (volume + 100) / 340 return out
58ee7f00c54b063fac23eeb166df5f6d6adb2941
20,840
def default_func(entity, attribute, value): """ Look in the entity for an attribute with the provided value. First proper attributes are checked, then extended fields. If neither of these are present, return False. """ try: return getattr(entity, attribute) == value except Attrib...
0ec6636c20d3f5eedb7a7c1f2457f72ecddb7545
20,852
def get_last_file(paths): """Returns last modified file from list of paths""" if paths: return sorted(paths, key=lambda f: f.stat().st_mtime)[-1] return ""
51978ae6dbb3686de40eebda156825904895a854
20,853
from inspect import signature def check_callable(input_func, min_num_args=2): """Ensures the input func 1) is callable, and 2) can accept a min # of args""" if not callable(input_func): raise TypeError('Input function must be callable!') # would not work for C/builtin functions such as numpy.dot...
7358d0685fd6f04f6a2ecf75aee66288a25a5e08
20,854
def evaluate_svm(test_data, train_data, classifier, logfile=None): """ Evaluates svm, writes output to logfile in tsv format with columns: - svm description - accuracy on test set - accuracy on train set """ train_x, train_y = train_data classifier.fit(train_x, train_y) test_x, tes...
21550a91227eca49a05db2f3216bc72c50a74d1e
20,861
def flatten_results(results: dict, derivation_config: dict) -> dict: """Flatten and simplify the results dict into <metric>:<result> format. Args: results (dict): The benchmark results dict, containing all info duch as reduction types too derivation_config (dict): The configuration ...
045c1e1d856c20b37d2d78d8dd6c3fd76cb91777
20,862
def path_string(obj, **kwargs): """return physical path as a string""" return "/".join(obj.getPhysicalPath())
bae683d392b519f8c43f5e9d1415abb8cf8de636
20,865
def adjust_returns_for_slippage(returns, turnover, slippage_bps): """Apply a slippage penalty for every dollar traded. Parameters ---------- returns : pd.Series Time series of daily returns. turnover: pd.Series Time series of daily total of buys and sells divided by portfoli...
d445bf566f5c228ffda793089d7bfe23f3897df2
20,869
import requests def get_json(url): """Fetches URL and returns JSON. """ res = requests.get(url) res.raise_for_status() return res.json()
280f3c298cb5a471abe180b29c9d465d52b7b9b8
20,870
def find_matching_resource(preview_resource, delivery_entry, search_field): """Returns matching resource for a specific field. :param preview_resource: Entry from the Preview API to match. :param delivery_entry: Entry to search from, from the Delivery API. :param search_field: Field in which to search ...
518297f18a2dcd37bb226f96bd51370d7ed3c7e3
20,872
import re def extract_date(text): """ Given the HTML text for one day, get the date :param text: HTML text for one day :return: Date as string """ report_date = re.findall("Arrow Build Report for Job nightly-.*", text)[0] report_date = report_date.strip("Arrow Build Report for Job nightly-...
e73952c4efc421f9227dad16346e923590933bdf
20,875
def __validate_scikit_params(parameters): """validate scikit-learn DBSCAN parameters Args: parameters: (dict) Returns: eps, min_samples, metric, n_jobs """ eps, min_samples, metric, n_jobs = None, None, None, None if parameters is not None: eps = parameters.get('eps') ...
9b1f9bf89f6526bb0b67d658dd1bfc6d69a8ad83
20,880
import json def load_json_key(obj, key): """Given a dict, parse JSON in `key`. Blank dict on failure.""" if not obj[key]: return {} ret = {} try: ret = json.loads(obj[key]) except Exception: return {} return ret
d695d8eb1d08933a3bacba4de77161a6587a863d
20,886
def float_to_fixed_point(x: float, precision: int) -> int: """ Converts the given floating point value to fixed point representation with the given number of fractional bits. """ multiplier = 1 << precision width = 16 if precision >= 8 else 8 max_val = (1 << (width - 1)) - 1 min_val = -...
8b80f701b610da06ac8a09e8811ce00967a1a413
20,887
def encode(s): """ Encodes a string into base64 replacing the newline at the end. Args: s (str): The string. """ return s.strip().encode('base64').replace('\n', '')
02c805b7888560596cede9c763d0cf42334d4185
20,889
def format_file_date(edition_date): """Return a string DDMMYY for use in the filename""" return edition_date.strftime('%d%m%y')
3cab0a2de4c91ae66826f4ba49d9e4fdc1b7c1d0
20,890
def parse_repo_url(repo_url: str) -> str: """ Parses repo url and returns it in the form 'https://domain.com/user/repo' Args: repo_url (str): unformatted repo url Returns: str: parsed repo url """ repo = repo_url.lstrip("git+") if repo_url.startswith("git+") else repo_url r...
5f9b5d2a0bc3dc30e48006fd43baa73d996268ca
20,896
def organism_matches(organism, patterns): """Tests organism filter RegEx patterns against a given organism name.""" for pattern in patterns: if pattern.match(organism): return True return False
135b6ad0472a2b0904ececc8b8f226c77b2294e6
20,897
from typing import Optional from typing import Dict def type_filter(type_: Optional[str], b: Dict) -> bool: """ Check Mistune code block is of a certain type. If the field "info" is None, return False. If type_ is None, this function always return true. :param type_: the expected type of block (...
083c89f9563c9282edf1babf9fdf249f694a0117
20,906
from typing import List def elements_identical(li: List) -> bool: """Return true iff all elements of li are identical.""" if len(li) == 0: return True return li.count(li[0]) == len(li)
2cccfaf588994080033e4ddfd17c351f5c462546
20,908
def read_file(filepath): """Open and read file contents. Parameters ---------- filepath : str path to a file Returns ------- str contents of file Raises ------ IOError if file does not exist """ file_data = None with open(filepath, "r") as f...
5b4e65893c94c45bb697a41222dbe524d60d2b04
20,910
def format_date(date:str) -> str: """return YYYYmmdd as YYYY-mm-dd""" return f"{date[:4]}-{date[4:6]}-{date[6:]}"
dfcc434006df8a7f6bd89003f592792faa891f30
20,911
def _get_bootstrap_samples_from_indices(data, bootstrap_indices): """convert bootstrap indices into actual bootstrap samples. Args: data (pandas.DataFrame): original dataset. bootstrap_indices (list): List with numpy arrays containing positional indices of observations in data. ...
15dac498120db5590bc3c8c2542c0d78be999dd4
20,914
def get_module_name_parts(module_str): """Gets the name parts of a module string `module_str` in the form of module.submodule.method or module.submodule.class """ if module_str: parts = module_str.split('.') module_name = '.'.join(parts[:-1]) attr_name = parts[-1] values ...
f167fe3a1224b5d3a1909e66bb9fa5288fd23eae
20,915
from typing import List def blocks_to_squares(blocks: List[List[int]]) -> List[List[List[int]]]: """Returns a list of list of blocks of four squares at a time. E.g. .. code-block:: python blocks = [ [A, B, 1, 1], [C, D, 0, 1], ] # would return the list below ...
5bdde168ef9309ff93d478c6e6776d250c832c37
20,916
def server(app): """Return a test client to `app`.""" client = app.test_client() return client
aeef67904f95d28356989ddbde49a43378fa096f
20,920
def middle(a): """Returns a (list) without the first and last element""" return a[1:-1]
112854e009afaf6080363f3f1b3df944b4739ede
20,922
import unicodedata import re def ascii_uppercase_alphanum(s, decoding='utf-8'): """Convert a string to alphanumeric ASCII uppercase characters.""" if type(s) is float: return s nfkd = unicodedata.normalize('NFKD', s) only_ascii = nfkd.encode('ASCII', 'ignore') upper = only_ascii.upper() ...
3694581fae9935a332e2929364e96eb054b3e749
20,926
def _add_tags(tags, additions): """ In all tags list, add tags in additions if not already present. """ for tag in additions: if tag not in tags: tags.append(tag) return tags
234e6cabd478bcfc95bb3d8f6118e0f0307fabc4
20,929
def get_cmdb_detail(cmdb_details): """ Iterate over CMDB details from response and convert them into RiskSense context. :param cmdb_details: CMDB details from response :return: List of CMDB elements which includes required fields from resp. """ return [{ 'Order': cmdb_detail.get('order'...
aa2750b3754d2a776d847cfa22ff2b84f53bb351
20,932
def sqr(num): """ Computes the square of its argument. :param num: number :return: number """ return num*num
cb16d5638afeff0061415e45467b5fd4e644951f
20,935
def cidr_to_common(cidr_mask): """Function that returns a common mask (Ex: 255.255.255.0) for a given input CIDR mask (Ex: 24)""" cidrtocommon = { 1: "128.0.0.0", 2: "192.0.0.0", 3: "224.0.0.0", 4: "240.0.0.0", 5: "248.0.0.0", 6: "252.0.0.0", 7: "25...
9357592b86c812d632edcbe376d55994c58174b6
20,936
def pluralize(n, s, ss=None): """Make a word plural (in English)""" if ss is None: ss = s + "s" if n == 1: return s else: return ss
1b24a513f1529666f8535a17482f1ce1b140d1ef
20,939
def serialize_profile(user_profile): """ Serializes an user profile object. :param user_profile: user profile object :return: dictionary with the user profile info """ return { 'bio': user_profile.bio, 'description': user_profile.description, 'resume': user_profile.resume...
4eb1f88c197117c9dd31ab3090d541c0ae7b65bb
20,941
def ensure_list(thing): """ Wrap ``thing`` in a list if it's a single str. Otherwise, return it unchanged. """ if isinstance(thing, str): return [thing] return thing
45ac322794627661c814b7905d6531aedd2a61b5
20,948
def create_acc_ui_command(packer, main_on: bool, enabled: bool, stock_values): """ Creates a CAN message for the Ford IPC adaptive cruise, forward collision warning and traffic jam assist status. Stock functionality is maintained by passing through unmodified signals. Frequency is 20Hz. """ values = { ...
2a0ab397b54d328e6af38701caec002ca7fa99ac
20,951
import re def cleanup_tex_line(text): """Format line of tex e.g. replace multiple spaces with one""" # replace multiple spaces with 1 space (simplifies matching) if text == r"\n": return "" text = re.sub(r" {2,}", " ", text) text = text.rstrip() return text
0304477aafa447a3aad58da116cac2590437351d
20,952
import json def humanreadable_from_report_contents(contents): """Make the selected contents pulled from a report suitable for war room output Parameters ---------- contents : dict Contents selected from an ANYRUN report for Demisto output. Returns ------- dict Contents fo...
852be1990fff7832ff73f1853b756ddf1b34ec33
20,953
def get_id(mention): """ Get the ID out of a mention as a string :param mention: String of just the mention :return: Snowflake ID as an int """ return int(mention.strip("<@#&!>"))
eb7dcfd8ae5752318e646218219c8faaf6348d19
20,956
import math def to_deg_min_sec(DecDegrees): """ Converts from decimal (binary float) degrees to: Degrees, Minutes, Seconds """ degrees, remainder = divmod(round(abs(DecDegrees), 9), 1) minutes, remainder = divmod(round(remainder * 60, 9), 1) # float to preserve -0.0 return math.copy...
52ac22a4d504c264260a812d43b7bf850c7f1595
20,962
import re def cleanId(input_id) : """ filter id so that it's safe to use as a pyflow indentifier """ return re.sub(r'([^a-zA-Z0-9_\-])', "_", input_id)
a53b93945754dec2c79039e9fe2720f3472248cc
20,963
import torch def predict(model, dataloader, labeldict): """ Predict the labels of an unlabelled test set with a pretrained model. Args: model: The torch module which must be used to make predictions. dataloader: A DataLoader object to iterate over some dataset. labeldict: A dictio...
c2e28c9dacca715720186c2ce01735cb4a7c2e38
20,964
def target_fasta(tmp_path): """A simple target FASTA""" out_file = tmp_path / "target.fasta" with open(out_file, "w+") as fasta_ref: fasta_ref.write( ">wf|target1\n" "MABCDEFGHIJKLMNOPQRSTUVWXYZKAAAAABRAAABKAAB\n" ">wf|target2\n" "MZYXWVUTSRQPONMLKJIHG...
a0aead0b8aab69d3d9b2805b26fcad94ea9e5b8d
20,967
def simple_mutation(image, base_image, sequence, calculate_error, palette, draw): """Computes the effects of a simple mutation. :param image: The image to draw the gene on. :param base_image: The original image to compare to. :param sequence: The gene sequence. :param calculate_error: The error met...
7f39cfcf877f55b4f3072ac1762470d7d38d33e7
20,969
import time def should_refresh_time(event_time, last_refresh_time, refresh_after_mins=60): """ The clock on the PyPortal drifts, and should be refreshed from the internet periodically for accuracy. We want to refresh the local time when: - The local time isn't set - After refresh_after_mins h...
a785714b5efeafe8250f4fe841d2d0e085ba197f
20,973
def map_skip_none(fn, it): """ emulate list(map(fn, it)) but leave None as it is. """ ret = [] for x in it: if x is None: ret.append(None) else: ret.append(fn(x)) return ret
296110c3d416d1653411da7c3fbce02b280078b1
20,974
def shoot_error(x_target, x): """ calculates the error of a shoot on the target at x_target. :param x_target: position of the target :param x: state array holding the complete history of the shoot :return: error. A positive sign of the error indicates that the shoot has been to far, a negative sign ...
d03e07cb4779cedbf485e4ebd55869c5f9471d29
20,981
def parse_mapholder_div(tree): """Parses the HTML for a 'mapholder' class. Parameter --------- tree: lxml.html.HtmlElement The section in the HTML page for each map. This is normally <div class="mapholder"> ... </div> Return ------ Dictionary object with the specified f...
6f211eb5341de1d59e9043d2cc9c4b0340a8bd50
20,982
from typing import Iterable def last_survivor(letters: str, coords: Iterable[int]) -> str: """ Removes from letters the chars at coords index. Returns the first survivor letter. """ arr = list(letters) for idx in coords: del arr[idx] return arr[0]
21d2ddb7bfb43a8df5eca390b1154a1a863ed373
20,987
def pred_sql(col, val): """ Generates SQL for equality predicate. Args: col: predicate restricts this column val: filter column using this value Returns: predicate as SQL string (escaped) """ esc_val = str(val).replace("'", r"''") return f"{col}='{esc_val}'"
16dd042820fc0cef3139320e204646c3c678bd0e
20,988
import random def block(n_subjects, n_groups, block_length, seed=None): """ Create a randomization list using block randomization. Block randomization takes blocks of group labels of length `block_length`, shuffles them and adds them to the randomization list. This is done to prevent long runs of a ...
d42601d3861f86f7eac4c7525d78e1b4dd4ef81a
20,990
def get_number_features(dict_features): """Count the total number of features based on input parameters of each feature Parameters ---------- dict_features : dict Dictionary with features settings Returns ------- int Feature vector size """ number_features = 0 f...
6f81c359cfee77896cb8e4334aa23cf977aaca5a
20,991
def save_gpf(df, output_file): """ Write a socet gpf file from a gpf-defined pandas dataframe Parameters ---------- df : pd.DataFrame Pandas DataFrame output_file : str path to the output data file Returns ------- int : success ...
fb551a8e5a3861939bd40cbfcb5a82bd6cc88161
20,993
def next_node_of_edge(node, edge): """ Return the node of the edge that is not the input node. :param node: current node :type node: Node object :param edge: current edge :type edge: Edge object :return: next node of the edge :rtype: Node object """ # If the input node ...
2fd226802ba504bfa7f950d0c69defc79a45e049
20,994
from typing import List def consec_badpixels(bad_pixels: List[List[int]]) -> bool: """Check for consecutive bad pixels in the same nod. Consecutive in in axis=1 for the same axis=0 value. parameters ---------- bad_pixels: list of list of ints List of index locations of bad pixels [nod, p...
a14e994151c12fa04dca4ce5f6e143d652264dc7
21,004
def format_pfrule(pfrule): """Render port forwarding option.""" format_str = '-{0.pf_type} {binding}'.format return format_str(pfrule, binding=pfrule.binding) if pfrule else ''
a8e7bec5818586aac945c48ff5553f38f5c444d6
21,008
def _is_ref(schema): """ Given a JSON Schema compatible dict, returns True when the schema implements `$ref` NOTE: `$ref` OVERRIDES all other keys present in a schema :param schema: :return: Boolean """ return '$ref' in schema
1f805929a6b28cf4fbe16714d300f3beffeb6e73
21,015
def add_one(number): """ Example of a simple function. Parameters ---------- number: int, float, str Returns ------- out: int, float, str The input value plus one. Raises TypeError if the input is not the expected type """ if isinstance(number, (float, int)): ...
d24a5d9e1a02098d1a6638bdc8b5493bc4d732e2
21,016
import json def load_settings(settings_fname='settings.json'): """ Загрузить настройки из файла Parameters ---------- settings_fname : str Имя файла с настройками, по умолчанию имя файла: settings.json Returns ------- username : str ...
63067d6d351bbe799f5e9a839c9e7fba92fe54ef
21,017
def eval_cluster(labels, cluster_id, is_clean): """ Evaluate true positives in provided cluster. :param labels: (np.ndarray) array of labels :param cluster_id: (int) identifier of the cluster to evaluate :param is_clean: (array) bitmap where 1 means the point is not attacked :return: (int) number o...
1499d705bf6a250e214b5f6cac9f1daa3a22d30f
21,019
def iter_dicts_table(iter_dicts, classes=None, check=False): """Convert an iterable sequence of dictionaries (all of which with identical keys) to an HTML table. Args: iter_dicts (iter): an iterable sequence (list, tuple) of dictionaries, dictionaries having identical keys. classes (str...
e1be3d05180eef1a9a039011007413d4fec65301
21,020
def filter_post_edits(dict_elem): """ Filter post history events that modified the body of the posts. :param dict_elem: dict with parsed XML attributes :return: boolean indicating whether element modified the body of the corresponding post """ return int(dict_elem['PostHistoryTypeId']) in [2, 5,...
b8f567d6dceb0dd1deb6cffac631bfc44f0fb282
21,023
def split_str(string: str, maxsplit: int = 1) -> list: """ Splits characters of a String into List of Strings :param string: String to split :param maxsplit: It is the number of skips in character before splitting, DEFAULT = 1 :return: Returns the Array containing elements of characters splitted fro...
0d0e2a43c03009c85b2e2fcfa0df8ac4bd241787
21,026
import collections def items_to_dict(l, attrs='name', ordered=False): """Given a list of attr instances, return a dict using specified attrs as keys Parameters ---------- attrs : str or list of str Which attributes of the items to use to group ordered : bool, optional Either to re...
0948ab89944319887661804c78c995adcf306695
21,028
def median(seq): """Returns the median of a sequence. Note that if the list is even-length, then just returns the item to the left of the median, not the average of the median elements, as is strictly correct. """ seq = sorted(seq) return seq[len(seq)//2]
c463fa83908606472ead5ef7d56d8b72c7c34edd
21,033
def AddFieldToUpdateMask(field, patch_request): """Adds name of field to update mask.""" update_mask = patch_request.updateMask if not update_mask: patch_request.updateMask = field elif field not in update_mask: patch_request.updateMask = update_mask + "," + field return patch_request
f8533b38e3ecf7658aa06850869727ab3f34e7de
21,038
def sub_from_color(color, value): """Subtract value from a color.""" sub = lambda v: (v - value) % 256 if isinstance(color, int): return sub(color) return tuple(map(sub, color))
71be1ef8f956ec2c9fdee0516a01833922934aa7
21,050
import re def replace_with_null_body(udf_path): """ For a given path to a UDF DDL file, parse the SQL and return the UDF with the body entirely replaced with NULL. :param udf_path: Path to the UDF DDL .sql file :return: Input UDF DDL with a NULL body """ with open(udf_path) as udf_file: ...
7a014192b4623ed90f04b50fe52dceb696355c9c
21,052
def create_login_url(path): """Returns the URL of a login page that redirects to 'path' on success.""" return "/auth/hello?redirect=%s" % path
0ba50d443d8cddbbc77ada8a0828cf5a0e534ef1
21,053
def option_name_to_variable_name(option: str): """ Convert an option name like `--ec2-user` to the Python name it gets mapped to, like `ec2_user`. """ return option.replace('--', '', 1).replace('-', '_')
abaf2bb749eed54372233db677f9668c2d486f29
21,062
def file_unload(file: str): """ Open text file, read it's contents and write unpack them into list. :param file: str -- name of the config file :return: list -- list of lines read from the file """ unpacked_file = [] with open(file, "r") as f: for line in f: if line.star...
7bdc61b662796ec2fd7324d4d6934755dc9a2ab7
21,075
def ez_user(client, django_user_model): """A Django test client that has been logged in as a regular user named "ezuser", with password "password". """ username, password = "ezuser", "password" django_user_model.objects.create_user(username=username, password=password) client.login(username=user...
20e54603e8154cbf9f6c7e0cbd06a78627beecd0
21,077
def _split_left(val, sep): """Split a string by a delimiter which can be escaped by \\""" result = [] temp = u"" escaped = False index = 0 left = True for c in val: left = False temp += c if c == sep[index] and not escaped: index += 1 else: ...
c85d8e0e07b9a99ad3f299f44d722c514a11935a
21,079
def parent_directory(path): """ Get parent directory. If root, return None "" => None "foo/" => "/" "foo/bar/" => "foo/" """ if path == '': return None prefix = '/'.join(path.split('/')[:-2]) if prefix != '': prefix += '/' return prefix
261943945531fc348c46c49f5d3081cbd815bfdb
21,083