content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Union from typing import Tuple def parse_lat_lng(kwargs) -> Union[Tuple[float, float], Tuple[None, None]]: """Parses latitude and longitude values stated in kwargs. Can be called with an object that has latitude and longitude properties, for example: lat, lng = parse_lat_lng(objec...
24414d624132ed506f967c9dfcef64e35530c3b5
634,129
import os def splitpath(path): """Splits a path into all its components""" p0,p1,p = (*os.path.split(path),tuple()) while p1!='': p0,p1,p = (*os.path.split(p0),(p1,) + p) return p
96febc287aec4a4752d04068990a3a950a2463aa
634,130
import torch def evaluate(net, dataloader, criterion, device, adv=False): """Evaluate network.""" net.eval() val_loss = 0 val_correct = 0 val_total = 0 with torch.no_grad(): for batch_idx, (inputs, targets) in enumerate(dataloader): inputs, targets = inputs.to(device), tar...
66c0635eb35e00af42f4c9966e9e05df1178065b
634,131
import os def get_test_name(main__file__): """extract the name of the main test script Args: main__file__ (str): __file__ of the main script Returns: str: Name of the test """ test_fname = os.path.splitext(os.path.basename(main__file__))[0] test_name = test_fname if test...
4421a8b36a3d36bede74e454e6330397dbafdc21
634,132
def header(): """ Returns a standard warning that can be placed at the top of each generated _Fortran_ include file. """ return """ ! ------------------- ! W A R N I N G ! ------------------- ! ! This code fragment i...
4c98ef21a32693e901cc6c3895e4acbdcab9feb8
634,134
def polynomial_3(x, a, b, c, d): """Polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3""" return a + x * (b + x * (c + x * d))
ff7d51b96580d6f053c4874dc4d8af1260a0139c
634,135
def get_config_part(config_parent, match_key, match_value): """ helper function to filter a dict by a dict key :param dict_: ``dict`` :param key: dict key :param value: dict key value :returns: filtered ``dict`` """ return {k: v for (k, v) in config_parent.items() if v[match_key] == m...
d92a5ad9135df3fb827701ecf0fdc31ba69c4f8d
634,136
from typing import MutableMapping def test_mock_nested_dict() -> MutableMapping: """Mock nested dictionary.""" return {"a": 1, "c": {"a": 2, "b": {"x": 5, "y": 10}}, "d": [1, 2, 3]}
29b12b28f02238ef91767af235d865ec04a19568
634,138
def _get_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_va...
4644549803c16e310677ce6b0cd9770d0299a02c
634,139
from typing import Union import re def extract_id_from_message(content: str) -> Union[int, None]: """ Scans string to extract user/guild/message id\n Can extract IDs from mentions or plaintext :return: extracted id """ # matching string that has 18 digits surrounded by non-digits or start/end ...
dfee4595efea16f56c11cf66a4ea8ebb0dcd7313
634,140
import requests import json def getReqJSON(url, args={}): """Generic function to get json from an api request""" if url.endswith("/"): url = url[:-1] arg_str = "" if isinstance(args, dict): if len(args) > 0: arg_str = "?" + "&".join([str(k) + "=" + str(args[k]) for k in ar...
48cb495976aca490242987460676cbe655d88ab9
634,141
import functools def db_wrapper(method): """Decorator that is used to create the appropriate cursor for the table and call the database method with it. Args: method: Method to decorate. Returns: Decorated method. """ @functools.wraps(method) def _db_wrapper(*pargs, **kargs): table_class = ...
255c3df59566e72793c0532fcfd5284e776c4ca5
634,142
def update_item(status): """input put upload status to DynamoDB""" return dict( Key={"PK": status.uri, "SK": status.timestamp}, UpdateExpression="SET #status=:status", # status is reserved ExpressionAttributeNames={"#status": "status"}, ExpressionAttributeValues={":statu...
15f124b277936492a1bc542080e2f16fb6e2d1a7
634,144
def geojson_crs(epsg): """Generate a GeoJSON CRS member from an EPSG code.""" epsg = int(epsg) if epsg == 4326: coordinate_order = [1, 0] else: coordinate_order = [0, 1] return { 'type': 'EPSG', 'properties': {'code': epsg, 'coordinate_order': coordinate_order}}
a2b962d260594e1c73bd700665b1f61375c8a4df
634,145
def page_not_found(e): """Return a custom 404 error.""" return '<h1>Sorry, nothing at this URL.<h1>', 404
f40fafec4a9df8a073d0efaf2fb2411531b1977a
634,146
def use_numpy(request) -> bool: """ Compare ExtensionDtype and numpy. Boolean fixture to support comparison testing of ExtensionDtype array and numpy array. """ return request.param
72766717d9f99b6a2544b7aa003546791e771338
634,147
import re import unicodedata def slugify(name, allow_periods=False): """ Returns a tuple with slug and lowered slug based on name """ RE_NON_ALPHA_ETC = re.compile(r'[^.\w]+' if allow_periods else r'[^\w]+') slug = RE_NON_ALPHA_ETC.sub('-', # replace non ". alphanum_" sequences into single - ...
4b6ecff0f3e4b356b20d6d3ef1ddb336dba76d81
634,148
def make_bigly(name: str) -> str: """A function returning a string, rather than a component.""" return f"BIGLY: {name.upper()}"
fffcb1be1bc4e4efdd9d8b0bc8bb0459b830c4a2
634,149
import re def load(path, mode='r', encoding='shift-jis', remove_blankline=True, oremo=False): """ 録音リストを読み取ってオブジェクト生成 path : 録音リストのパス mode : ファイルをopen()するときののモード rmblank : 空行を削除するかどうか oremo : 録音ソフトウェア「OREMO」用のコメントの有無。あるならTrue """ # 録音リストのデータ用リスト l = [] # OREMOのコメントを無視す...
72839d858642d5fe1ab25159c2403487577c2b51
634,150
def sqkm2sqmiles(field_name, item, **kwargs): """ Convert square killometers to square miles """ sqkm_field = kwargs['source'] sqkm = item[sqkm_field].replace(',','') return '{:,}'.format(int(float(sqkm)*0.386102159))
c676e433352f1f6fb3fffe1a8c3b20ad5e3a6a1f
634,151
def _to_status_class(class_name: str) -> str: """Renders the class object into its corresponding status class.""" remaps = { "LocalSubjectAccessReview": "SubjectAccessReviewStatus", "SelfSubjectAccessReview": "SubjectAccessReviewStatus", "SelfSubjectRulesReview": "SubjectRulesReviewStatu...
ada7b12c17372324e7964ac0b6b5c7b8680fcf3e
634,152
import torch def inverse_weighted_mse_loss(pred, label, mean, norm=15): """inverse weighted""" length, dim = pred.size() delta = norm // 2 + 1 - torch.abs(label - mean) * norm * 1.0 delta = delta.clone().detach() delta.data.clamp_(1.0, 10.0) term1 = torch.sum((pred - label) ** 2 * delta) / len...
cf1007332f962e2d7e8c9606792f021c66dbaaee
634,153
def factorial_recursion(number): """ >>> factorial_recursion(3) 6 >>> factorial_recursion(5) 120 >>> factorial_recursion(0) 1 >>> factorial_recursion(1) 1 """ if isinstance(number, float) is True: raise ValueError("Non integer number is not allowed") if number < 0...
aeeb42db7a29792e9edf6480c7764852fe885505
634,154
def smartctl_get_status(smart: dict) -> str: """ Get disk status from smartctl output. This algorithm has been mined: it's based on a decision tree with "accuracy" criterion since seems to produce slightly better results than the others. And the tree is somewhat shallow, which makes the algorithm more ...
d98cce07473e15f88c192e3c9f624e1d499d64d1
634,155
import inspect import warnings def check_model_functionality(model_object: object, require_probabilities: bool = False, suppress_warning: bool = False) -> bool: """ Checks whether a model object has all the required functionality. Examines a ``m...
e44ed26b519cde1bcb7011074840f17185a62cd7
634,156
import json def load_config(): """ Load config.json :return: Dict """ with open('config.json') as config: return json.load(config)
5090c804968bc63baaaf72f83d43f0f67b5bcfad
634,157
def parse_dereplicated_uc(dereplicated_uc_lines): """ Return dict of seq ID:dereplicated seq IDs from dereplicated .uc lines dereplicated_uc_lines: list of lines of .uc file from dereplicated seqs from usearch61 (i.e. open file of abundance sorted .uc data) """ dereplicated_clusters = {} see...
14431c9da4909c10787649da8ba30922607e2890
634,158
def adlist_top3_by_comment(cur): """ top 3 adlists by comment """ sql = "SELECT comment, count(*) FROM adlist GROUP BY comment LIMIT 3" cur.execute(sql) return cur.fetchall()
af04a6ad4bd991521b527ae8e237142cafe707c8
634,159
import re def word2num(word: str) -> str: """Encode a word after removing non-word characters. Ex: "Don't" -> "Dont" -> '405'.""" # remove non-alphabetic chars from the given word cleaned_word = re.sub('[^a-zA-Z0-9]', '', word) return str(sum(map(ord, cleaned_word)))
a9d16519518d20be1b6b8ca3b5782c03fb50256b
634,160
import torch def lengths_to_mask(*lengths, **kwargs): """ Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[ True, False, False], [ True, True, False], [ True, True, True]]) >>> lengths_to_mask([1, 2, 2], ...
5b26e91bba7110a7421723f628924d9656cb007d
634,161
import unittest def expected_failure(test_item): """ Expect the test case to failure :param test_item: :return: """ return unittest.expectedFailure(test_item)
760f28259317810548b9b375b6b84ed608ab78af
634,162
from typing import Any from typing import List def to_list(obj: Any) -> List: """Converts an object to a list. If the object is already a list, does nothing. :param obj: Object to convert """ return obj if isinstance(obj, list) else [obj]
67951b4d01267d594231dd04bb2b7930a392f849
634,163
import re def split_column_name(column): """Split column name into a (name, unit) tuple.""" match = re.match(r"\s*([^ ([<]+)\s*[([<]?([^] )>]*)[])>]?", column) if not match: return column, "" name, unit = match.groups() return name, unit
baff57c42c6005e95bafb83206bd301fdb79c4c0
634,164
import math def jw_sim_py( first, second, # modification from original to not use other imput parameters ): """ Jaro-Winkler similarity calculated exactly as in stringutils.similarity_jaro_winkler in Apache Commons using a modified version of the algorithm implemented by 'Jean-Bernard Ratte - jea...
fc9db56f90beaa731681bc16460266374aed8333
634,165
from typing import Callable from datetime import datetime def on_date(month: int, day: int) -> Callable[[datetime], bool]: """ Filter that allows events that match a specific date in any year Args: - month (int): the month as a number (1 = January) - day (int): the day as a number Re...
4f2c166a12505b1d1e0e9aec55e06e0e94d5efc7
634,167
def a_source_username(plugin_ctx, fsm_ctx): """send source username.""" src_username = plugin_ctx.src_username fsm_ctx.ctrl.sendline(src_username) return True
c24c759ea6bc8025a48e75e8377025272a408ab0
634,169
def _right_parser(tab, i): """Helper function to build google observations """ coord = [] tab_ = tab[i]["right_team_positions"] for list_ in tab_: for value in list_: coord.append(value) return coord
2ac8443a87f5b2fa4347543af5ea64cd162da990
634,170
def _IsLoopConstantEnter(op): """Returns true iff op is a loop invariant.""" is_enter = (op.type == "Enter" or op.type == "RefEnter") return is_enter and op.get_attr("is_constant")
9696a6aa89de5cadcbd7333fa09d383dd1d24610
634,171
def sum_list_1(dataset: list) -> int: """Вычисляет сумму чисел списка dataset, сумма цифр которых делится нацело на 7""" sum_result = 0 for dataset_elem in dataset: sum_numbers = 0 dataset_elem10 = dataset_elem while dataset_elem10 // 10 > 0: sum_numbers += dataset_elem10...
826bfea1df07bd0bd0a0a82ed6c89709eabbe89b
634,172
import argparse import sys def parseArgs(args=None): """Parse the terminal arguments args - arguments list to be parsed, None means sys.argv """ # formatter_class=argparse.ArgumentDefaultsHelpFormatter parser = argparse.ArgumentParser(description=' Sample entities from the input RDF dataset' ' producing the...
95b1c8766031ac60b8efe0b42e73e657ebfa47ee
634,173
def filter_datastores_by_hubs(hubs, datastores): """Get filtered subset of datastores corresponding to the given hub list. :param hubs: list of PbmPlacementHub morefs :param datastores: all candidate datastores :returns: subset of datastores corresponding to the given hub list """ filtered_dss ...
79278802dde4d46293d90df5375f225e8d2858f6
634,174
from typing import List def _length_of_longest_path(file_paths: List[List[str]]) -> int: """Determines the length of the longest path out of all the paths Args: file_paths (List[List[str]]): a list containing all file paths which are lists of the parts Ex.: [['home', 'usr', 'dir1'], [...
ecab8673f0d1c6220104423a48c0975340db7263
634,176
def create_skill_mix_vars(model, shifts, shift_days, skill_mix_rules): """Create skill mix variables.""" skill_mix_vars = { (day, shift, rule_num): model.NewBoolVar( f"day:{day}_shift:{shift}_rule:{rule_num}" ) for shift in shifts for day in shift_days[shift] ...
20f2521741167d082c633a3817f003bc5a7d1674
634,177
def _resource_id_from_record_tuple(record): """Extract resource_id from HBase tuple record """ return record[1]['f:resource_id']
e35a780201d465783558e7e41cd3e1f1d37ff239
634,178
import sys def verify_python_version(): """Ensure the script is being run in python 3.6""" try: # use assert to throw an exception if # the python version is less than 3.6 assert sys.version_info >= (3, 6) return True except AssertionError: return False
584fbb3b5741b7f8fe441b100f65f6afc0970177
634,180
def is_following(user_, other_user): """Is this user following `other_use`?""" found_user_list = [user for user in user_.following if user == other_user] return len(found_user_list) == 1
e9f56a756690807dfd1c140d0631092e0d3a462d
634,181
def _identity_dynamics(x): """Returns same input as output.""" return x
53b8612fec76e464608d17b2d4d37331ba760e9d
634,183
def toHours(spec): """spec is of the form '08:00-10:00' """ return (int(spec[0:2])+int(spec[3:5])/60.0, int(spec[6:8])+int(spec[9:11])/60.0)
525dbca1e98267dab7e8ec5137b00bec4dad1cd0
634,184
def normalize_ip(ip): """ Transform the address into a fixed-length form, such as:: 192.168.0.1 -> 192.168.000.001 :type ip: string :param ip: An IP address. :rtype: string :return: The normalized IP. """ theip = ip.split('.') if len(theip) != 4: raise ValueError(...
2b810e71befe544291d743492196065d5963a3d7
634,185
def _var_key(var): """Key for representing a primary variable, for looking up slots. In graph mode the name is derived from the var shared name. In eager mode the name is derived from the var unique id. If distribution strategy exists, get the primary variable first. Args: var: the variable. Returns:...
77f45e0030488eab2d446b9bd8eca1432ffd365a
634,186
from collections import OrderedDict import json import os def parse_model_desc(model_desc_path): """Parse a model description file for building DL models for QC Parameters ---------- model_desc_path : str - Path to json file containing info (see example below. Both mo...
427d85be56a3e8e2feacc0a55ef27ac9fd9a95cb
634,187
def has_abba(code): """Checks for existence of a 4-letter palindromic substring within `code` The palindromic substring must contain 2 unique characters """ palindrome = None for i in range(len(code) - 4 + 1): # substring = code[i:i + 4] if code[i] == code[i + 3] and code[i + 1] == c...
a1a8235165ae99a7a8d2d26a778bbdcdaca592c6
634,188
import re def hex_to_bytes(hexstring: bytes) -> bytes: """Convert a hexadecimal string to a byte string. This allows to render space-friendly byte strings when encoding. :param hexstring: The hexadecimal string to convert :type hexstring: bytes :return: The converted string :rtype: bytes ...
abb90174b6afc14cf855a15c2d074b64293b9ea2
634,189
def is_crf(model): """ checks for CRF sequence tagger. """ # loss = model.loss # if callable(loss): # if hasattr(loss, '__name__'): # loss = loss.__name__ # elif hasattr(loss, 'name'): # loss = loss.name # else: # raise Exception('could not get loss name') # return loss =...
73429d58f4658082c3a3513f9a88827a3806820d
634,190
import ast def genAssignStraight(to: ast.Name, fieldName: str, processorFunc: ast.Attribute, o: ast.Name) -> ast.Assign: """Returns `to.fieldName = processorFunc(o.fieldName)`""" return ast.Assign( targets=[ast.Attribute(value=to, attr=fieldName, ctx=ast.Store())], value=ast.Call( func=processorFunc, arg...
70dabfd90cdc04c8038b70372bbd1b938059c203
634,191
import logging def removePvProperty(cf, pvname, prpt, prptval): """remove pv property""" cfprpt = cf.find(name=pvname, property = [(prpt, prptval)]) if cfprpt is None: logging.warn("'%s' has no property {'%s': %s}" % (pvname, prpt, str(prptval))) return False cf.d...
37d78a477079c758434efc8d88e7d219118d57c7
634,192
def trsamplebins(dbin, t0, t1, sta, chan, binsize, apply_calib = False, filter = None): """Return binned time-series data for a given station, channel, and time-interval""" return dbin.samplebins(t0, t1, sta, chan, binsize, apply_calib, filter)
e2e9a066e4cadb0ad9f71d63d44ab607d4a83af9
634,193
def deploy_contract(revert_chain, deploy_contract_txhash): """Returns a function that deploys a compiled contract""" def fn( web3, deployer_address, abi, bytecode, args, ): contract = web3.eth.contract(abi=abi, bytecode=bytecode) tx...
b040d2ef50273860aa73271f744ef86918bd972e
634,194
def min_encoded_value(n_bits): """The minimum value encoded by a signed bit-width.""" return 0 if n_bits >= 0 else -(2 ** (abs(n_bits)))
36b52c4db902dc0548f8c18cee45042b7626551b
634,195
import math def fix_cook_value_in_jail_data(jail_data, booking_value=math.nan, adp_value=math.nan): """Revise Cook County's records in jail data.""" try: fixed = jail_data.copy() c_cook = fixed['fk_simplecount_county'] == 16 c_booking = fixed['fk_simplecount_indicator'] == 1500 ...
92c1a76229687ed9d15a57460c89753d7a86ede5
634,196
import re def fixXmlText(msg): """ Removes unallowable characters from xml @ In, msg, string, tag/text/attribute @ Out, msg, string, fixed string """ # replace illegal characters with "?" # from http://boodebr.org/main/python/all-about-python-and-unicode#UNI_XML RE_XML_ILLEGAL = u'([\u0000-\u000...
458804d45b9661668b281aff758354fc1c02dcb9
634,197
from typing import List def get_paragraphs(text: str) -> List[str]: """ Returns a list containing all paragraphs. Input(s): 1) text - Original source text. Output(s): 1) paragraphs - List containing all paragraphs. """ paragraphs = text.splitlines() paragraphs = list(filter(lamb...
9c5da93a3ee8cb9befc225742231f965cea610c8
634,199
import re def get_name_and_email(address): """ Function to get name and email from addresses like Company <contact@company.com>, returned as tuple (name, email) """ custom_sender_name = re.search(r'^([^<>]+)\s<([^<>]+)>$', address) if custom_sender_name: return custom_sender_name.group...
20cc05de3317ffc8d7bd7724ab61296e01f1c532
634,200
def build_rst_table(rows, titles): """Build an rst table from a table of entries (i.e. list of lists)""" ncols = len(titles) assert all(len(row) == ncols for row in rows) lengths = [max(map(len, col)) for col in zip(*rows)] def make_line(row, fill=' '): return ' '.join(entry.ljust(length, ...
a0298cbd26480313d487ee2c94ab01092d04d75e
634,201
def get_page_content(ctx, title): """Retrieves the full content of the page identified by the title. Currently this will only return content for the current page. This returns None if the page is other than the current page, and False if the page does not exist (currently not implemented).""" assert...
caa785befb938c1ab7418252d3fcc26ba7e977b6
634,202
import base64 def s_to_b64s(s: str) -> str: """convert string to base 64 string :param s: input string :type s: str :return: output base 64 string :rtype: str """ b64s = base64.b64encode(s.encode('utf8')).decode('utf8') return b64s
8498ff7365fbcc104ed138c61b543450c7d470f1
634,203
def format_error_message(exception_message): """Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. Args: exception_message...
8723962be0ef70edd0b996a3b503b4793dd10016
634,204
from typing import Sequence from typing import List def make_beat_cycle( beat_cycle: Sequence, num_bars: int, ) -> List: """Given a beat cycle, extends it for the given number of bars. """ result = [] i = 0 while i < num_bars: bar = [] for j in range(beat_cycle[i % len(be...
0096c5d0f0dc0e53d0297d3e6bfa782a6a418310
634,205
from typing import Any from typing import AnyStr from typing import Tuple async def async_fetch(session: Any, url: AnyStr) -> Tuple[AnyStr, Any, Any]: """Asynchronous I/O HTTP GET request with a ClientSession instantiated from the aiohttp library.""" async with session.get(url) as response: status...
f7ae04b7a7cfcc157aa69df6489809f409b84607
634,206
def trim(s: str) -> str: """ Remove leading spaces """ for i, c in enumerate(s): if c != ' ': return s[i:] return ''
47aad91d4e8cd44e76a0eacd62ce532cecd6640e
634,208
def climb(n, steps): """ 一个共有 10 个台阶的楼梯,从下面走到上面,一次只能迈 1-3 个台阶, 并且不能后退,走完这个楼梯共有多少种方法 :param n: 第 n 个台阶 :param steps: 可以走的步数 :return: 第 n 个台阶有多少种走法 """ count = 0 if n == 0: count = 1 elif n > 0: for step in steps: count += climb(n - step, steps) retu...
a7ea18a181f768a435bfd1d7b91f15440c69073b
634,210
def __check_pattern(node): """ check if pattern attribute is set and defines the extension """ if node.tag != "discover_datasets": return False if "pattern" not in node.attrib: return False if node.attrib["pattern"] == "__default__": return True if "ext" in node.attri...
556759232a08cd07a2eedc3b00355f3f12b82f21
634,212
def tree2str(node, labeled=True): """ Parameters ---------- node: NonTerminal or Terminal labeled: bool, default True Returns ------- str """ if node.is_terminal(): return "%s" % node.index inner = " ".join([tree2str(c, labeled=labeled) for c in node.children]) ...
d4ecb9f21c5b98445ebad51c84402840313ac192
634,213
def events_for_forms(events_array): """parse each event in the events array (from the database) into a ISO datetime range string, returning an array sorted oldest/newest. """ events = [ "{0}/{1}".format(e['dt_start'], e['dt_end']) for e in events_array ] events.sort() return events
c128c390848ac935f2b11028dca0a3affed8dc47
634,214
def _should_relaunch_killed_pod(evt_obj): """ Check whether to relaunch the failed pod according to the kubernetes event. For the killed pods, we will try to relaunch them except the OOM ones. """ return ( evt_obj.status.container_statuses and evt_obj.status.container_statuses[0]...
656f568996ce3c71a140a49a3fc44f974a71f237
634,215
def breadcrumbs(context, root, current_page, show_home=True): """Returns the pages that are part of the breadcrumb trail of the current page, up to the root page.""" pages = current_page.get_ancestors( inclusive=True).descendant_of(root).filter(live=True) return { 'request': context['re...
f63169733493fa800169a7b0280c0d6ce45f95c6
634,216
def module_path_from_object(o): """Returns the fully qualified class path of the instantiated object.""" return o.__class__.__module__ + "." + o.__class__.__name__
44eac16ce5c68a71a5d6bc797b8d69896b90bc8b
634,217
def is_nested(value): """Returns true if the input is one of: ``list``, ``unnamedtuple``, ``dict``, or ``namedtuple``. Note that this definition is different from tf's is_nested where all types that are ``collections.abc.Sequence`` are defined to be nested. """ return isinstance(value, (list, tuple,...
9824b06fcd2f96b6a6c6e1414845d3610daf5aea
634,218
import json def read_bundles(bundle_list_file): """Read bundles in to a dict from a file. This function expects the JSON file follows a pre-defined schema: [ {"bundle_uuid": XXX, "bundle_version": XXX}, {"bundle_uuid": XXX, "bundle_version": XXX} ] Args: b...
3e95def0ff01e25deafb3637bc5ec86850a2832c
634,219
import json def login_response_to_authorization_header(response): """ given a response from login or register, return a dictionary containing a header for Authorization """ return dict( Authorization='Bearer ' + json.loads( response.data.decode() ...
15e7d96fe5ae4df78001f675aa34aab517e7444a
634,220
from typing import Tuple def extract_hosts_from_arm(arm: str) -> Tuple[str, str]: """Arm names have the following format: host1.metric1-host2.metric2 Extracts and returns the name of the two hosts from the arm them. The names of the host might be the same. Args: arm (string): Name of the a...
41b7b3eb6ba6959773653d32bc854bd15bdbeb90
634,221
def _callable_prefix(bot, message): """Callable Prefix for the bot.""" user_id = bot.user.id base = [f"<@!{user_id}> ", f"<@{user_id}> "] if not message.guild: base.extend(bot.def_prefix) else: base.extend(bot.def_prefix) return base
032241430be5c0075796812d940ae060258898c6
634,222
import mmap def file_contains(path, needle): """Check if the file residing on the given path contains the given needle """ # Since we have no idea if build.log is valid utf8, let's convert our ASCII # needle to bytes and use bytes everywhere. # This also allow us to use mmap on Python 3. # Be ...
87a8f7eca6f7db90fc2b27214b02947560a5956c
634,223
def __find_frequent_subsequences(sequences): """Tries to find frequent subsequences in the specified list of sequences. """ passes = set() for sequence in sequences: for p in sequence: passes.add(p) passes = list(passes) subsequences = [] for p in passes: subse...
5b798346342b0b50be4dd2975c81445760cfcb05
634,224
def increments(data): """ sums up all incrementing steps in list so: if x2 > x1 : increments += (x2-x1) else : do nothin """ return float(sum([data[index + 1] - data[index] for index in range(len(data)-1) if data[index + 1] > data[index]]))
f1ef23dc640b1c1fec942cce4df71a7202467879
634,225
def parse_str(value: str) -> str: """ Clean string. :param str value: Original str. :return: str: Cleaned str. """ return value.strip()
edf951982274b8f803f5152dcec9297a38de10e9
634,226
import os def load_words(filename): """ Loads words from csv to list """ words = [] dirname = os.path.dirname(__file__) csvfile = open(os.path.join(dirname, filename), 'r') for line in csvfile: words.append(line.strip()) csvfile.close() return words
9cbc3d6201329a6562cb4da4bba0f252152fc411
634,228
def nested_result(): """ >>> nested_result() [[], [-1L], [-1L, 0L], [-1L, 0L, 1L]] """ result = [[a-1 for a in range(b)] for b in range(4)] return result
94d5978b7f7265ad3e3355d135a11981bcbf10b7
634,229
import ast def parse_webhook(webhook_data): """ This function takes the string from tradingview and turns it into a python dict. :param webhook_data: POST data from tradingview, as a string. :return: Dictionary version of string. """ data = ast.literal_eval(webhook_data) return data
021950c233a35433a7431c871dc6c5381954ebc7
634,230
def users_to_string(users): """ Return users emails with <br> element for using them in tooltip's title. User will hover over the text and see all emails. """ to_return_string = "" for user in users: to_return_string += user.email + "<br/>" return to_return_string[:-5]
a4d51408372388f22b983d1974f965cb624123f8
634,231
def source_ip(source_list): """Returns the source IP address, byte 26 - byte 29""" output = "" for i in range(26,30): output += str(int(source_list[i], 16)) + "." return output[:-1]
7195d7198a85f8a35897c420e1d12987127f7e37
634,232
def onedim_conversion(length_or_speed: float, mm_per_pixel: float): """ :param length_or_speed: in [px] or [px/s] :param mm_per_pixel: in [mm/px] :return: length i [mm] or speed in [mm/s] """ return length_or_speed * mm_per_pixel
0eb707b0946fb917a7f93df62819a15b28135170
634,235
def concatenateDates(fullDates, yearMonthDates, years): """This function combines several dates in a human readable fashion. >>> concatenateDates(set(['1988-04-25']), set(['1988-05']), set()) '1988-04-25 or 1988-05' >>> concatenateDates(set(['1988-04-25', '1988-04-24']), set(['1988-05']), set()) '1988-04-24...
9289d8cf39ec8e6ea4cc8c91a08d325a8d788600
634,236
import argparse def create_arg_parser(): """"Creates and returns the ArgumentParser object.""" parser = argparse.ArgumentParser(description='Script to swap faces between two images.') parser.add_argument('from_image', help='Path to first image where you will extract the face.') parser.add_argument('to...
780b8a84e24fc0846a46a4a03321ff4a89559031
634,237
def before_mixin_sdel(sdel_mixin, *args, **kwargs): """Called immediately before Nova's models.SoftDeleteMixin.soft_delete, it prepares the expected kwargs (as in the original method). """ # Ensure the arguments expected by SoftDeleteMixin.soft_delete if 'session' not in kwargs: kwargs['sess...
74aa5550409409afc7bcd1eb916d931e00248350
634,238
import logging def get_root_logger(): """Get main Ralph logger""" ralph_logger = logging.getLogger("ralph") ralph_logger.propagate = True return ralph_logger
f5b993c63589b1bbabe1f67b26eb28a3319c7e7e
634,239
def _border_properties_to_styles(properties): """ Convert the properties to border styles. :param properties: Ordered list of OOXML properties :return: dictionary of border styles """ styles = {} # - 'border-top', 'border-right', 'border-bottom', 'border-left' for style, prop in prope...
df575fe21d5e24ef501007419541dcfc7be14d20
634,240
from typing import Tuple def hdf5_01_encode(uid: str, cksum: str, dset: int, dset_idx: int, shape: Tuple[int]) -> bytes: """converts the hdf5 data has spec to an appropriate db value Parameters ---------- uid : str the file name prefix which the data is written to. cksu...
e06977e53ee822eeabe5a95fc34bbce4b9ebf603
634,241
def verify_variant_type(variants, variant_type, pos, length): """"Helper function for checking a specific variant type. Args: variants: List of variants to look through. variant_type: The type of variant to verify. pos: Position of the variant. length: Size of the variant. ...
cfb0d6cd13198e0c8731650e28aafa9c4944e302
634,242
def UniquifyCombinations(combos): """ uniquifies the combinations in the argument **Arguments**: - combos: a sequence of sequences **Returns** - a list of tuples containing the unique combos """ print('>>> u:', combos) resD = {} for combo in combos: k = combo[:] k.sort() r...
1360c8ee1ebb475922440766e3a7f509c6f3bf6c
634,243