content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def has_time_layer(layers): """Returns `True` if there is a time/torque layer in `layers. Returns `False` otherwise""" return any(layer.time for layer in layers if not layer.is_basemap)
0351fa97cab084b90e836f624a86baf8922861a1
673,684
def is_storage(file, storage=None): """ Check if file is a local file or a storage file. Args: file (str or int): file path, URL or file descriptor. storage (str): Storage name. Returns: bool: return True if file is not local. """ if storage: return True eli...
2b4355e4efba38aef2ce5a5961e6013947b3cd94
673,687
def flatten(x): """flatten(sequence) -> list Return a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples:: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,No...
d435e06613671b1786dcc6de18804ff83d4fa808
673,688
def minimum_distance(mp, ip, dp, i): """ Compares each element from the distance profile with the corresponding element from the matrix profile. Parameters ---------- mp: numpy.array Matrix profile. ip: numpy.array Index profile. ...
62cd66a15a3d3cf526c7eaca1f10fd5f56bde8f5
673,693
def convert_duration(milliseconds): """ Convert milliseconds to a timestamp Format: HH:MM:SS """ # it's easier to wrap your head around seconds seconds = milliseconds / 1000 hrs = seconds // 3600 mins = (seconds % 3600) // 60 s = (seconds % 3600) % 60 return "{:02}:{:02}:{:02}"...
dea6f0d09a0b53e193c1c0cfdf4f844f9da9bb65
673,696
def rivers_with_station(stations): """Returns a set containing all rivers which have a monitoring station. Params: Stations - List of all stations. \n. Returns: {River 1, River 2, ... } """ rivers = set() # set for station in stations: # iterate and add rivers to set r...
9422ecfade5fe19ce162911294abbd00e4444820
673,697
def place_mld_breakpoints(incompt_pos :list): """ Adds an MLD breakpoint in the middle of an incompatible interval. Parameters: incompt_pos (list): chop_list() output Output: list: indexes of MLD breakpoints in the sequence """ return [int(inter[0] + (inter[...
c194c879bc49ebda6bbaf8cadce44852b1ff73aa
673,698
def list_drawings_from_document(client, did, wid): """List the drawings in a given workspace""" # Restrict to the application type for drawings res = client.list_elements(did, wid, element_type='APPLICATION') res_data = res.json() drawings = [] for element in res_data: if element['dataTy...
1d52169616688dbcde50761d89e7db17cde6a617
673,701
def read_order(order_file): """ Read the order of the API functions from a file. Comments can be put on lines starting with # """ fo = open(order_file, 'r') order = {} i = 0 for line in fo: line = line.strip() if not line.startswith('#'): order[line] = i ...
76d688fb780a3251a027f108127e7314e7c95b69
673,702
def add_spaces_to_fill(text, places): """Adds blank spaces to a string so that the length of the final string is given by 'places'. """ return text + (places-len(text))*" "
26b12e84b90fd331fdc8e1fd97d9680f050c9afe
673,704
import time def _invoke_timed_callback( reference_time, callback_lambda, callback_period): """Invoke callback if a certain amount of time has passed. This is a convenience function to standardize update callbacks from the module. Args: reference_time (float): time to base `callback_p...
44397d5c70d747966c83714a8ed17f9c3109de7c
673,707
def remove_entity_from_list(unique_list, i): """ Removes all instances of a particular entity from a list >>> remove_entity_from_list(['test', 'test', 'three'], 1) ['three'] """ return [x for x in unique_list if x != unique_list[i]]
ae66405b76842693ab629a8cd8ebc3d7ec145a24
673,708
def _tbl_str_width(num, widths): """Returns the width-argument for an html table cell using the width from the list of widths. Returns width="[some number]" or the empty-string if no width is specified for this num""" if num >= len(widths): return "" return ' width="%s"' % widths[num]
3d35c82033ae504eeac143f35653303f1425da60
673,710
import shutil def center_text(msg: str, *, pad: str = ' ') -> str: """Centers text horizontally for display within the current terminal, optionally padding both sides. :param msg: message to display in the center :param pad: if provided, the first character will be used to pad both sides of the message ...
3ead8c3bce298d779205bf0d6743ec6ac05c4d7a
673,711
import typing def _parse_config_file(content: str) -> typing.Mapping[str, str]: """Parses an ini-style config file into a map. Each line is expected to be a key/value pair, using `=` as a delimiter. Lines without `=` are silently dropped. """ kv = {} for line in content.splitlines(): if not line or l...
b55a263aaeccb860d9212d35277df0db39893435
673,713
def get_same_padding_for_kernel_size(kernel_size): """ Returns the required padding for "same" style convolutions """ if kernel_size % 2 == 0: raise ValueError(f"Only odd sized kernels are supported, got {kernel_size}") return (kernel_size - 1) // 2
2c0c142d785ea1659f0bb03c22bfa1c972ae2e3d
673,714
def _remove_output_cell(cell): """Remove the output of an ipymd cell.""" cell = cell.copy() if cell['cell_type'] == 'code': cell['output'] = None return cell
f4d19cc1c9d9b63988508d4dcc1f70ea68ef6716
673,717
from typing import Tuple from typing import Optional def _parse_hp_template(template_name) -> Tuple[str, Optional[int]]: """Parses a template name as specified by the user. Template can versionned: "my_template@v5" -> Returns (my_template, 5) or non versionned: "my_template" -> Returns (my_template, No...
2225eef7b2f21f5e5180b686261a1f413312b848
673,719
def PyUnixTimeConv(some_DT_obj): """ func to convert DateTime Obj to Unix Epoch time, in SECONDS, hence rounding""" output_unix_time = some_DT_obj.timestamp() return round(output_unix_time)
657f6c34ee9cc9b98681ba2519e843466d1a01b6
673,721
import json def to_json(raw_data): """ Pretty-prints JSON data :param str raw_data: raw JSON data """ return json.dumps(raw_data, sort_keys=True, indent=4, separators=(',', ': '))
9faf1a31e2f906e8170226d81160a5523c201566
673,725
import re def get_sleep_awake_folder(s): """Get the if animal is sleeping from folder""" temp = re.split("_|\.|\ |\/", s.lower()) if "sleep" in temp or "sleeping" in temp: return 1 return 0
06c797da20273c3c316fda55db9be142a8a08ad9
673,728
def make_tuple(str_in): """ makes a tuple out of a string of the form "(a,b,c)" """ str_in = str_in.strip("()") l = str_in.split(",") return tuple(l)
d7ae58a3c618edbff3d2a83b72350d6ad32b1a3a
673,730
def rotate_ccw(str_array: list[str]) -> list[str]: """ Rotate a list of strings quarter-turn counter-clock-wise :param str_array: array as a list of strings :return: array rotated counter clock-wise """ zip_array = list(''.join(c) for c in zip(*str_array)) ccw_rot_array = zip_array[::-1] ...
a8bd4d70856c5c9c48d7b3778f14ceb0a2cbeb20
673,731
def get_object_name_from_schema(obj: object) -> str: """ Returns the name of an object based on type. This is used to return a userfriendly exception to the client on bulk update operations. """ obj_name = type(obj).__name__ to_remove = ["Base", "Create", "Update"] for item in to_remove:...
6e1d33f915ba6265bbea143b3e7c8b64fa06faab
673,732
def normalize_description(description): """ Normalizes a docstrings. Parameters ---------- description : `str` or `Any` The docstring to clear. Returns ------- cleared : `str` or `Any` The cleared docstring. If `docstring` was given as `None` or is detected as e...
4ece93902474f53ecce92cb3c902b0157beca733
673,733
def max_counts(ng1, ng2): """ Return a dicitonary of ngram counts such that each count is the greater of the two individual counts for each ngram in the input ngram count dictionaries /ng1/ and /ng2/. """ ret = ng1.copy() for k, v in ng2.items(): ret[k] = max(ret.get(k, 0), v) ...
d1c1b78353a1c07070b240b7806b753bd071a122
673,736
def turn(n): """Formula from WIkipedia. n could be numpy array of integers """ return (((n & -n) << 1) & n) != 0
b37e26fff265be114427fa1657e878eaa1b773a2
673,737
def ratio(x,y): """The ratio of 'x' to 'y'.""" return x/y
70b044627a75dd6fc583a84b87014bbade9b18c1
673,742
import operator def sequence_eq(sequence1, sequence2): """ Compares two sequences. Parameters ---------- sequence1 : sequence The first sequence. sequence2 : sequence The second sequence. Returns ------- bool `True` iff `sequence1` equals `sequence2`, othe...
3e6520602272873f471c808ad14c6d3a90d31972
673,743
import re def fix_tx_name(tx): """Remove the .[0-9] at the end of RefSeq IDs.""" if tx.startswith('NM'): return re.sub('\.[0-9]$', '', tx) else: return tx
68fae9ffd80b47da3d36ac919fa5a4ca2ad9a14f
673,750
def simple_call_string(function_name, argument_list, return_value=None): """Return function_name(arg[0], arg[1], ...) as a string""" call = function_name + "(" + \ ", ".join([var + "=" + repr(value) for (var, value) in argument_list]) + ")" if return_value is not None: ca...
bd5c026f9bf573cbdb99e25872851f46e1218b09
673,755
def get_ticket_url_from_id(ticket_id): """ Get the associate ticket id :param ticket_id: `str` ticket_id :return: `str` ticket url """ return "https://jira.com/id={0}".format(ticket_id)
33a5b7994dc477a9e32d634728ffc6cda42b6d6d
673,756
def _q_start(query_seq, q_seq): """ returns the starting pytyon string index of query alignment (q_seq) in the query_sequence (query_seq) :param query_seq: string full query sequence :param q_seq: string alignment sequence (may contain gaps as "-") :return: :example: >>_q_start(query_seq = ...
25882b80e2adb2ac95cf238c23d0a0afb1e69f9b
673,757
from typing import List def set_ignored_keys(**kwargs) -> List[str]: """ Lets users pass a list of string that will not be checked by case-check. For example, validate_response(..., ignore_case=["List", "OF", "improperly cased", "kEYS"]). """ if 'ignore_case' in kwargs: return kwargs['igno...
9a753f560d36ce4fc28450907f2eb1d6e3306e9a
673,758
def ft2m(ft): """feet -> meters""" return 0.3048*ft
8ab872d97eb8adcc2cbf72bae270ea5e9045a5ff
673,760
def format_labels(labels): """ Convert a dictionary of labels into a comma separated string """ if labels: return ",".join(["{}={}".format(k, v) for k, v in labels.items()]) else: return ""
44a1f649fd6f9d9d18212e725cb40ce1dab99a18
673,761
def _refresh_candles(candle: dict, candlelist: list[dict], max_len: int = 10000) -> tuple[list[dict], bool]: """Recieve candlestick data and append to candlestick list if it is new candlestick.""" changed = False if candle['k']['x']: if candlelist: if candle['k']['t'] != candlelist[-1]['...
0f898036e0dbf660ef91482e28bc5e95631b08ed
673,762
def get_string_for_language(language_name): """ Maps language names to the corresponding string for qgrep. """ language_name = language_name.lower().lstrip() if language_name == "c": return "tc-getCC" if language_name == "c++" or language_name == "cxx": return "tc-getCXX" if ...
a90f2bbaf1c73832cc0f6057dc9ac812024523d8
673,769
def _trc_filename(isd, version): """ Return the TRC file path for a given ISD. """ return 'ISD%s-V%s.trc' % (isd.isd_id, version)
01205a1cde280d7f7fd046906e2919d973752707
673,771
def get_recs(user_recs, k=None): """ Extracts recommended item indices, leaving out their scores. params: user_recs: list of lists of tuples of recommendations where each tuple has (item index, relevance score) with the list of tuples sorted in order of decreasing relevance ...
490d0473e640c70457aa69a9af7dc7a4269e39d3
673,772
import torch def polar_to_rect(mag, ang): """Converts the polar complex representation to rectangular""" real = mag * torch.cos(ang) imag = mag * torch.sin(ang) return real, imag
840039244b303b3f176fbaa29d2ab52d400eb04b
673,773
def get_contactinfo_tuple(member, considerNoPublish=False): """Returns tuple with the member's contact information If considerNoPublish is True a member with noPublishContactInfo_fld == 1 will get empty contact information fields. """ contactinfo = member.contactinfo department = '?' try: ...
48eb20d0ec4befeb1791fbc407fc7d55f5fd8c7e
673,775
import re def regex_escape(string): """Escape all regular expressions special characters from STRING.""" return re.escape(string)
16af3984ee43515b9f0cc2089bcfecf590331cdb
673,776
from datetime import datetime def is_valid_isodate(date: str, check_timezone: bool = False) -> bool: """Check if a string is a valid ISO formatted datestring""" dt = None try: dt = datetime.fromisoformat(date) except ValueError: return False if check_timezone: if dt.tzinf...
212c16236c79ef51d369cef18401cfcfd89e246f
673,779
def _append_notes_to_markdown(*, markdown: str, notes: str) -> str: """ Append a notes string to a specified markdown string. Parameters ---------- markdown : str Target markdown string. notes : str Target notes string. Returns ------- markdown : str Result ...
399e9361be9317961a1d071dc36bfb1de49a7161
673,780
def inhg_to_hpa(value: float) -> float: """Convert an inHg value to hPa.""" return value * 33.8639
1c1366646d3a74059251d9e263c807689c6fd87a
673,782
import re def determine_file_extension_from_response(response): """ This retrieves the file extension from the response. :param requests.Response response: the response object from the download :return the extension indicating the file compression(e.g. zip, tgz) :rtype str """ content_disp...
dd5fd45ef44eea4911331ca463054d0433fb83d9
673,783
import traceback def format_last_exception(prefix=" | "): """Format the last exception for display it in tests. This allows to raise custom exception, without loosing the context of what caused the problem in the first place: >>> def f(): ... raise Exception("Something terrible happened") ...
03506e79fba39cca25d9af817750e7d6742a9603
673,784
def get_next_connection_index(db, profile_id, folder_path): """Finds next connection index Args: db (object): The db object profile_id (int): The id of the profile folder_path (str): The folder path used for grouping and nesting connections Returns: Next connection index va...
9d1d30e08833c5a09ca09a3a80e4a46dc04abd31
673,785
import re def splitcamelcase(string): """Transform CamelCase into camel case""" res = "" for ch in string: if re.match('[A-Z]', ch): res += ' ' + ch.lower() else: res += ch return res
be6e51c65174fc9542de05f04b6243147152a99b
673,789
def can_make_target_sum(integers, target): """Return True if a pair of integers that add up to `target` are found. The time complexity of this algorithm is O(N), where N is the number of integers in `integers`.""" complements = set() for i in integers: # O(N) complement = target - i # O(1)...
c9d92bd75e06457c01875fa82fcb3d9d9ba65de4
673,792
import itertools def flatten_list(lst): """concatenate a list of lists""" return list(itertools.chain.from_iterable(lst))
9134175bb322a8c11d2f30e6ba1d23fa075fc73d
673,793
def calculate_manhattan_dist(idx, value, n): """calculate the manhattan distance of a single tile""" goalRow = value // n #row index at goal goalCol = value % n #col index at goal currentRow = idx // n #current row index currentCol = idx % n #current col index dist = abs(goalRow - currentRo...
4952262666a1d8d4b6c93a436be092f9b50c0480
673,794
def parse_slots(content): """Parse the list of slots. Cleans up spaces between items. Parameters ---------- content: :class:`str` A string containing comma separated values. Returns ------- :class:`str`: The slots string. """ slots = content.split(",") retu...
45d8410be8a628c21d40bbb7d543da9e451d7650
673,795
def isfloat(in_str): """Check if a string can be cast to float""" try: float(in_str) return True except ValueError: return False
c06d46ea0b7fc8bfba9dcafe644bc878d138ab54
673,798
def get_primary_axis(hist): """Returns the highest dimension axis, e.g. if 1D histo this will return the y-axis. """ dim = hist.GetDimension() if dim == 1: return hist.GetYaxis() elif dim == 2: return hist.GetZaxis()
32099e76fc47081c15bd8f63ae04a11919e2b53e
673,800
def xtype_from_derivation(derivation): """Returns the script type to be used for this derivation.""" if derivation.startswith("m/84'"): return 'p2wpkh' elif derivation.startswith("m/49'"): return 'p2wpkh-p2sh' else: return 'p2pkh'
247a24644bb69e45b3b85f530594adfaa37e4afd
673,802
import json def load_entities(path): """ Load the entities and return an dict carrying all relevant info """ try: with open(path) as file: entities = json.loads(file.read()) ents = {} for e in entities['entities']: ents[e['entity']] = {'ope...
ddc82ea030af64a2b222ec18f7122833e495e2af
673,803
import re def ExtractThroughput(output): """Extract throughput from MNIST output. Args: output: MNIST output Returns: throuput float """ regex = r'INFO:tensorflow:global_step/sec: (\S+)' match = re.findall(regex, str(output)) return sum(float(step) for step in match) / len(match)
ba513b965fb8706bc2d113db3ce387f0565ae4cc
673,805
def hex2bytes(hex_str): """ Converts spaced hexadecimal string (output of ``bytes2hex()``) function to an array of bytes. Parameters ---------- hex_str: str String of hexadecimal numbers separated by spaces. Returns ------- bytes Array of bytes (ready to be unpicked). ...
7deb5fcc2e805eb8e82392d86f3adcc98b0e4365
673,806
def getfullURL(date): """Returns Congressional Record URL (of PDF record) for a given date.""" base_url = "https://www.gpo.gov/fdsys/pkg/CREC-"+date+"/pdf/CREC-"+date+".pdf" return base_url
36cf3160c0e1c8afe888ad9b001e5c9eac8bce03
673,807
import math def lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0): """Return a 1-dimensional Lorentzian function. lorentzian(x, amplitude, center, sigma) = (amplitude/(1 + ((1.0*x-center)/sigma)**2)) / (pi*sigma) """ return (amplitude / (1 + ((1.0 * x - center) / sigma) ** 2)) / (math.pi * sig...
b25721a6e69639206195799d6b69bdc0e9357b01
673,808
def index_sets(items): """ Create a dictionary of sets from an iterable of `(key, value)` pairs. Each item is stored in a set at `key`. More than one item with same key means items get appended to same list. This means items in indices are unique, but they must be hashable. """ index = {} ...
22184945b32857366cbfbfceba9d6fff2332c3fa
673,810
def _getAllSpacesInConstraint(spaceConstraintData): """ Return a combined list of native and dynamic spaces for a constraint. Args: spaceConstraintData (dict): The loaded space constraint data from the space constraint node Returns: A list of dict representing spaces applie...
f05b437d9233c9d5da36dfd69aaf45e132aafa17
673,812
def log_sum_exp(x): """calculate log(sum(exp(x))) = max(x) + log(sum(exp(x - max(x)))) """ max_score = x.max(-1)[0] return max_score + (x - max_score.unsqueeze(-1)).exp().sum(-1).log()
754b87d13043e63b928c63de453782b22d44c135
673,816
def run_command(command, args, cwd): """Runs a command with the given context. Args: command: ManageCommand to run. args: Arguments, with the app and command name stripped. cwd: Current working directory. Returns: 0 if the command succeeded and non-zero otherwise. Raises: ValueError: The ...
03c77b2e357acee0c1aad3fd6b5c0b092aa919b2
673,820
def divisible(a, b): """Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.""" return not a % b
1322afa568feaf440f5d73f8611e741a8b5d479f
673,821
def BitSet(x, n): """Return whether nth bit of x was set""" return bool(x[0] & (1 << n))
d331fe0d2f6367409bf1933954a9de3fb051446f
673,824
def get_corresponding_letter(index, sentence): """ Get the letter corresponding to the index in the given sentence :param index: the wanted index. :param sentence: the reference sentence. :return: the corresponding letter if found, 'None' otherwise. """ if index < len(sentence.letters): ...
4bc6df4228d2e8fc9fdd7ce2791c33d5f2a96257
673,829
from typing import Any from typing import Union from typing import Type from typing import Callable def try_else(source: Any, target_type: Union[Type, Callable], default_type: Union[None, Type, Callable] = None) -> Any: """ try to do something, and catch and return either some default operation, or the origin...
417e8846e4f457d6d3bcdb9ae296a4dc1da103f5
673,834
import torch def gpu_count(gpus: int) -> int: """ Find the number of GPUs to use. By default, the application attempts to use all GPUs available in the system but users can specify a different number of GPUs if desired. If the system doesn't have any GPUs available, it will default to the CPUs. I...
f835af6f989acc11baa76d63e25e1cf96b3d136f
673,835
def loc2Dict(loc): """ Convert a loc into a dictionary, for the consideration of maintainability. Parameters ---------- loc: list A location, in format of [lat, lon] or [lat, lon, alt] Return ------ dictionary A dictionary of location """ if (len(loc) == 2): locDict = { 'lat': loc[0], 'lon': loc...
2531cc2bec1c6acbb6999d19c7459da717c54a84
673,838
from typing import List def unique(object: List): """Remove duplicates from a list while preserving the order""" # list(set(object)) does the unique job, but it sets to random order u = [] for item in object: if item not in u: u.append(item) return u
666a768f4b5108e23f220662119df06e9eb38337
673,839
def _create_board(size=4): """Generating the empty starting game board This board can be of any (nxn) size. 0 = a space with no tile """ return [[0 for j in range(size)] for i in range(size)]
9ccacfbf5b8bd034aeb5d5498861223378de3c05
673,842
def apc(x): """Perform average product correct, used for contact prediction. Args: x: np array. Returns: apc np array """ a1 = x.sum(-1, keepdims=True) a2 = x.sum(-2, keepdims=True) a12 = x.sum((-1, -2), keepdims=True) avg = a1 * a2 avg.div_(a12) # in-place to red...
00c995d5a5aeb43ab6a0e33e1a4f64ee92a31ee9
673,843
from typing import Tuple from typing import Dict def key(product_: Tuple[str, Dict]) -> Tuple[float, float]: """Lemma 1 sorting key for the fixed attention problem. An optimal ranking for the fixed attention problem is sorted by this key function. Parameters ---------- product_: tuple[st...
21bdae856ba3bd6cb7796a99fd679cdeb66d7183
673,844
def unquote(s): """remove quotation chars on both side. >>> unquote('"abc"') 'abc' >>> unquote("'abc'") 'abc' >>> unquote('abc') 'abc' """ if 2 <= len(s) and s[0] + s[-1] in ['""', "''"]: return s[1:-1] else: return s
550065b9d74cd75db499f9156714634d1a37d9a4
673,846
def read_dict(filename, div='='): """Read file into dict. A file containing: foo = bar baz = bog results in a dict { 'foo': 'bar', 'baz': 'bog' } Arguments: filename (str): path to file div (str): deviders between dict keys and values Ret...
26bc9ec287d8e338cd7a5fef3a9f0de49ebf6138
673,856
import torch def numerically_stable_exp(tensor, dim=-1): """ Removes largest value and exponentiates, returning both. :param tensor: the input tensor :param dim: which is the dim to find max over :returns: exp(tensor - max), max :rtype: (torch.Tensor, torch.Tensor) """ max_value, _ = tor...
8cd7fae4c0a498a1b06b95f97c341f6147f21dbf
673,862
def median_manual(l): """ l: List of integers return median of list l """ n = len(l) l = sorted(l) if n%2 == 1: return l[int((n-1)/2)] return (l[int(n/2)-1] + l[int(n/2)]) / 2
63104190a38759563e8c003ac1c91ab8bbc78f89
673,867
def sink_for_card(card, pulse): """Return first sink that uses the given card otherwise return None""" sinks = pulse.sink_list() for sink in sinks: if sink.card == card.index: return sink return None
e877a745fd8376220f73cd0344c0a24292bc5ea9
673,875
def prepend(value, text): """ Prepends text if value is not None. """ if value is not None: value = str(value).strip() if value: return "{}{}".format(text, value) return ""
80f8067f467540a64cdaf4310407e675d4121696
673,881
import random def random_from_alphabet(size, alphabet): """ Takes *size* random elements from provided alphabet :param size: :param alphabet: """ return list(random.choice(alphabet) for _ in range(size))
aeb8e4f1609ab799dd2dd6d66b8bf266fcb34f20
673,883
def _str_to_list(val): """If val is str, return list with single entry, else return as-is.""" l = [] if val.__class__ == str: l.append(val) return l else: return val
6268db0a3f70215035783deeeec9859150c122e9
673,890
def integer_squareroot(n: int) -> int: """ Return the largest integer ``x`` such that ``x**2 <= n``. """ x = n y = (x + 1) // 2 while y < x: x = y y = (x + n // x) // 2 return x
894ac9ff8538dddf8b6c9d124f555182ca764a15
673,891
def is_threshold_sequence(degree_sequence): """ Returns True if the sequence is a threshold degree seqeunce. Uses the property that a threshold graph must be constructed by adding either dominating or isolated nodes. Thus, it can be deconstructed iteratively by removing a node of degree zero or...
ba00d6cf1eb943d28940e18faff6ca72b31eaae1
673,893
def crop_to_image_boundary(image, boxes, image_boundary): """Crop transformed image to original image boundaries (e.g., remove padding). Parameters ---------- image : np.ndarray Numpy integer array of shape (H, W, C). boxes : np.ndarray Numpy array of shape (N, 4), where N is th...
b1614f58dae4e64c001a401d3006e533a0651d8b
673,895
def following_mention_ids(api, ids): """ This function has the mention_ids and make sure if the account follow them if not ... don't make sense to unfollow them returns the ids list only with the ones that the account follow """ ids = list(set(ids)) following_mention_ids = [] ...
508032d92b563e8776c736404d6465d76c20a4a8
673,897
def Trim(t, p=0.01): """Trims the largest and smallest elements of t. Args: t: sequence of numbers p: fraction of values to trim off each end Returns: sequence of values """ n = int(p * len(t)) t = sorted(t)[n:-n] return t
53f10d3d25bc1ad351595fca7010d6c07cb3dacd
673,908
def show_volume(client, resource_group_name, name): """Show details of a volume. """ return client.get(resource_group_name, name)
10a529da1408037c2363183e48d3f69ffb473b4f
673,913
import torch def get_matrix_kernel(A, eps=1e-10): """ Compute an orthonormal basis of the kernel (x_1, x_2, ...) A x_i = 0 scalar_product(x_i, x_j) = delta_ij :param A: matrix :return: matrix where each row is a basis vector of the kernel of A """ _u, s, v = torch.svd(A) # A = u ...
0cfb55fd3431b19d6e3287708b31b4a2c04ece0c
673,915
def get_common_tables(old_conn, new_conn): """ a comparison function which checks for tables with the same name :param old_conn: the connection to the old db new_conn: the connection to the new db :return: A list of table names """ list_table_query = "select name from sqlite_ma...
00c19620c711c40e3081de3fcc64dd78235a6673
673,916
def get_iteration_prefix(i, total): """ Return a String prefix for itarative task phases. :param i int current step. :param total int total steps. """ return " [{0}/{1}]".format(i, total)
a1131b8ad931aaa07ccd8fb714ec91ddd985f0f3
673,917
from pathlib import Path def cp_path_to_dir(cp_path, tag): """Convert a checkpoint path to a directory with `tag` inserted. If `cp_path` is already a directory, return it unchanged. """ if not isinstance(cp_path, Path): cp_path = Path(cp_path) if cp_path.is_dir(): return cp_path ...
011ee9ee6ec72d34a1883eb98661c6d9024092f6
673,918
def join_extract(arr, attr_str, join_str): """Join the ``attr_str`` of the element of the ``arr`` with ``join_str``.""" return join_str.join([str(getattr(item, attr_str)) for item in arr])
f5d3f56e015402864176f1723288c148ca272cc6
673,919
def _key_case(arg: str): """Convert string to key_case. Only the non-prefix part of curies is retained all spaces and _ removed then all lowercased """ tmp = arg.split(':')[-1] tmp = ''.join(tmp.split(' ')) tmp = ''.join(tmp.split('_')) tmp = ''.join(tmp.split(',')) tmp = tmp.lo...
5e48429c3b53ff1ceafaef7c32577bb45a4851a8
673,920
def _CreateImage(media_service, opener, url): """Creates an image and uploads it to the server. Args: media_service: a ZeepServiceProxy instance for AdWords's MediaService. opener: an OpenerDirector instance. url: a str URL used to load image data. Returns: The image that was successfully upload...
d53b36320870d6dbc6c20d8e3cc5ac647cc91e21
673,922
def get_ann_energy_demands(city, print_out=False): """ Returns annual energy demands of city in kWh (space heating, electrical, hot water) Parameters ---------- city : object City object of pycity_calc print_out : bool, optional Print out results (default: False) Return...
cdb0603468be1e61e56c37c51ea630c9c2fdcbf1
673,923
def complex_abs_sq(data): """ Compute the squared absolute value of a complex tensor """ assert data.size(-1) == 2 return (data ** 2).sum(dim=-1)
e2a64d99b6a5dbad6b1239a0a876854db72d1a15
673,925
def format_cpf(value): """ This function returns the Brazilian CPF with the normal format. :param value is a string with the number of Brazilian CPF like 12345678911 :return: Return a sting with teh number in the normal format like 123.456.789-11 """ return f'{value[:3]}.{value[3:6]}.{value[6:9]...
d0b6c40244b0d75e690b214a998cd934c48194dc
673,926