content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def update_halley(yvals, y0): """Calculate the variable increment using Halley's method. Calculate the amount to increment the variable by in one iteration of Halley's method. The goal is to find the value of x for which y(x) = y0. `yvals` contains the values [y(x0), y'(x0), y''(x0), ...] of the functi...
c2021d0c21bd8a345da6808756c207a27afefeff
664,986
import torch def spatial_gradient(x: torch.Tensor, dim: int) -> torch.Tensor: """ Calculate gradients on single dimension of a tensor using central finite difference. It moves the tensor along the dimension to calculate the approximate gradient dx[i] = (x[i+1] - x[i-1]) / 2. Adapted from: ...
b60b2aa2b251dc0aa2ebc57eae25c17b436ba46d
664,991
def convert_by_vocab(vocab, items, unk_info): """Converts a sequence of [tokens|ids] using the vocab.""" output = [] for item in items: if item in vocab: output.append(vocab[item]) else: output.append(unk_info) return output
bf7b8cfab2e55a0c980efe055057194badf8ab09
664,992
def initialized(machine): """ Check to see if the given machine is initialized. :param machine: Machine to check to see if default attributes are set :return: `True` if the machine has its attributes set, `False` otherwise """ return all(hasattr(machine, attr) for attr in ('state', 'transition'...
a625827f7c53102a98521042a050e682df69b13e
664,995
def _read_nlines(filename, nlines): """ Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. """ if nlines < 0: with open(filename) as fh: return fh.readlines() lines = [] with open(filename) as fh: for lineno, line in enumerat...
d3e12f85f6be40c4f2f1644540d9d362a6c78672
665,000
def human_time(seconds): """Returns a human-friendly representation of the number of seconds.""" assert seconds >= 0 hours = seconds / (60 * 60) minutes = (seconds / 60) % 60 seconds = seconds % 60 return '%02d:%02d:%02d' % (hours, minutes, seconds)
ee339ab652a3a715a15514b2d40a75eb46f05e1f
665,001
def max_strand(dataset): """Returns the largest strand number in the supplied dataset""" return max(z.strand for z in dataset.zones())
fa6d5fb7a8f95a0dc323977377ad7979a66f8166
665,007
def overlap(a, b): """ Checks to see if two casings intersect, or have identical start/end positions. """ # If the casing start/end intersects intersect = (a[0] > b[0] and a[0] < b[1]) or (a[1] > b[0] and a[1] < b[1]) # If the casings start or end in the same place overlap = (a[0] == b[0]) o...
28d3382bb8ebd0fc12bb18c6311648d76f593bee
665,009
from typing import Tuple import math def rot( x: float, y: float, deg: float, origin: Tuple[float, float] = (0, 0) ) -> Tuple[float, float]: """ Rotate a point by `deg` around the `origin`. This does floating-point math, so you may encounter precision errors. """ theta = deg * math.pi / 180 ...
411c66982dcddf454372058595cc2c142b4d5fe7
665,010
import json def load_train_config(filename): """Load a configuration file.""" with open(filename, 'r') as f: config = json.load(f) return config
c60a6f5893cff1008ec7ed20f0afc3cd53bca388
665,011
def get_function_signature(func): """ Get the function signature as a mapping of attributes. :param func: The function object to interrogate. :return: A mapping of the components of a function signature. The signature is constructed as a mapping: * 'name': The function's defined n...
6a0b20b9979aae7b1808994d8452b5eb8c8bb00f
665,015
def run_plugin_action(path, block=False): """Create an action that can be run with xbmc.executebuiltin in order to run a Kodi plugin specified by path. If block is True (default=False), the execution of code will block until the called plugin has finished running.""" return f'RunPlugin({path}, {block})'
bac34fe4e68c417271ddc6966abcc045e5636fd8
665,017
def setup(df, params): """Calculate data series required for the backtest. Takes as input a dataframe with columns `['date', 'price_l', 'price_r']` and returns a dataframe with columns `['date', 'price_l', 'price_r', 'return_l', 'price_change_l', 'std_l', 'std_pcg_l', 'return_r', 'price_change_r',...
e1fdde0eee37ded99ba732c25561c59a639a1da0
665,018
import math import torch def construct_scale_pyramid(image, scale_factor=0.75, N=4, method='bicubic'): """ Constructs the scale pyramid :param image: normed image tensor with shape (N, C, H, W) :param scale_factor: float that indicates scale factor :param N: int that indicates the number of neede...
1ba0bb51e3d0384b0a6f8a8bda7d7ec9a06f6238
665,022
async def help_1(message, name): """Provides a description of a specific command.""" name = name.lower() return message.chat.commands.help(name)
931f7c6a34416b3401903ed65b24942b837a8de3
665,024
def read_file(filename): """ Read input file and save the crabs into a list. :param filename: input file :return: list of crabs """ crabs = [] with open(filename, 'r', encoding='UTF-8') as file: for line in file: for number in line.split(","): crabs.append...
0d06a6bcf98950474e1b2b38cc30697230acf742
665,025
def lat_fixed_formatter(y): """Simple minded latitude formatter. Only because those available in cartopy do not leave a blank space after the degree symbol so it looks crammed. If used outside this module, bear in mind this was thought to be used as part of an iterator to later be included in a ...
a47ac124bd5bdc5c3ee0feb529f28ba619f340d6
665,026
def calcWaterFractionByVolume(waterVolume, glycerolVolume): """ Calculates the volume fraction of water in a water - glycerol mixture Args: waterVolume (float): volume of water in l glycerolVolume (float): volume of glycerol in l Returns: :class:`float` Fraction of water by vol...
266eacb68e10b8943902f8a879ecc25ff4f77b14
665,028
def sorted_by_attr(vals, attr, reverse=False): """Sort sequence <vals> by using attribute/key <attr> for each item in the sequence.""" return sorted(vals, key=lambda x: x[attr], reverse=reverse)
ccf92f78c8cd79fd0cc7034de8ff55a93784e344
665,029
def level_dataset(lv): """Get dataset key part for level. Parameters ---------- lv : `int` Level. Returns ------- `str` Dataset key part. """ return '_lv%d' % lv
1ac7d0fc42b2d8d542fac4713d7e414ff8efb4c0
665,038
def predict(upstream, model): """Make a prediction after computing features """ return model.predict(upstream['join'])
1fab90a77e7e6923c7587b9e2e3f2cac7a6bf9b9
665,039
def user_input() -> int: """Displays a menu of the available actions and asks user's input :return sel: integer representing user's choice""" print("") print("=" * 50) print("1 - Collect images for calibration") print("2 - Perform calibration") print("3 - Disparity map tuning on sample imag...
f3d5a7d1f6a398f5c0fd84203c6c0d4d04fca780
665,040
def time_worked(clocked_in, clocked_out): """Return hours and minutes worked. Args: clocked_in: str, military time clocked_out: str, military time Returns: ( hours: int, count of hours, mins: int, count of minutes ): tuple """ section_time = la...
f2d9d1096811b1c9c13156a9bd17df6e31fcae47
665,041
def get_next_active_day(days, current_day, active_days): """Gets the next active day, often this will simply be the next day, i.e. if you set the active days as Mon - Fri and today is Mon, then the next active day is Tue. However is today is Fri then the next active day will be Mon. If say our active days ...
6f98e1a3c489e463b93617c97aab58bc4f7e8f55
665,044
def end_chat(input_list): """ End chat Parameters ---------- input_list : list List containing 'quit' to end chat. Returns ------- True or False : boolean Boolean assures whether to end chat based on whether the input contains 'quit'. """ if 'quit' in in...
bcf96aa2d3dc43c1d8464b9775c7450ebcf7984b
665,045
from typing import Mapping from typing import Any from typing import Dict def logs_as_floats(logs: Mapping[str, Any]) -> Dict[str, float]: """Convert Keras metric log values to floats.""" return {name: float(value) for name, value in logs.items()}
e65731f4dd13b9fcf61d331580440d77fd57c940
665,051
def _keys_to_byte(keys: list, default=b'\x00') -> bytes: """Return a byte in which the bits X are 1 for each X in the list keys.""" return bytes([sum(map(lambda b: 1 << b, keys))]) if keys else default
ef6c1cacfc10399189ed40235b5fdbc694acc73e
665,052
def byte_pad(data: bytes, block_size: int) -> bytes: """ Pad data with 0x00 until its length is a multiple of block_size. Add a whole block of 0 if data lenght is already a multiple of block_size. """ padding = bytes(block_size - (len(data) % block_size)) return data + padding
1839e36ab309e527d2832fabe190f884645fb5f2
665,054
def _has_no_variables(sess): """Determines if the graph has any variables. Args: sess: TensorFlow Session. Returns: Bool. """ for op in sess.graph.get_operations(): if op.type.startswith("Variable") or op.type.endswith("VariableOp"): return False return True
5db6d5d2485b49ad7d007f3b07519021b0de2732
665,056
def d_opt(param,value,extra_q=0): """ Create string "-D param=value" """ sym_q="" if extra_q==1: sym_q="\"" return("-D "+param+"="+sym_q+value+sym_q+" ")
04daa34d3eca92e60651e763ee08553acd9cf331
665,058
def merge_vals(current, update): """Update the current container with updated values. Supports dictionary, list and basic types, as well as nesting. :param current: the container to update :param update: the container to update with :return: updated container """ if current is None: # val...
4c4b8c641495b83c68b8abad6640c6ea53e465aa
665,060
from typing import Dict def get_271_member_not_found(demographics: Dict) -> str: """ Returns an Eligibility/271 response where a member is not found. :param demographics: Demographic fields included within the x12 response. :return: x12 transaction """ x12 = f"""ISA*00* *00* ...
189ba94782cbf126777a7f8903a0b06ae43260d8
665,061
def linspace(start, end, num=50): """ Return equally spaced array from "start" to "end" with "num" vals. """ return [start+i*((end-start)/float(num-1)) for i in range(num)]
906356e29cdbedc983bc70cb96f714c08e8e8a85
665,062
def panel_to_multiindex(panel, filter_observations=False): """Convert a panel to a MultiIndex DataFrame with the minor_axis of the panel as the columns and the items and major_axis as the MultiIndex (levels 0 and 1, respectively). Parameters ---------- panel : a pandas Panel filter_observa...
37a90ba6f7e9f1b022dc87c0d3b9524509a6742a
665,064
def get_steps_kwarg_parsers(cls, method_name): """ Analyze a method to extract the parameters with command line parsers. The parser must be a :class:`Param` so it handles parsing of arguments coming from the command line. It must be specified in the ``options`` class attribute. :param method_n...
5cc991c63c8008e92ff2bdc59c08ae1c96caa120
665,065
def set_buffer(library, session, mask, size): """Sets the size for the formatted I/O and/or low-level I/O communication buffer(s). Corresponds to viSetBuf function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :para...
01e496fb67f4fd74cfd6105899e5a100f0e77877
665,067
def safe_getattr(obj, attr_name): """Get the attribute of an object returning None if the attribute does not exist. :param obj: An object :type obj: mixed :param attr_name: The name of the attribute :type attr_name: str or unicode """ try: return getattr(obj, attr_name) exce...
9ed3eb8b0da04f65e3ac9316a2afa6c57648fd64
665,070
def GetHotkey(text): """Return the position and character of the hotkey""" # find the last & character that is not followed # by & or by the end of the string curEnd = len(text) + 1 text = text.replace("&&", "__") while True: pos = text.rfind("&", 0, curEnd) # One found was at ...
5fa03a1fe07c7f561143f9f64d5fd3908c86ae7f
665,077
import time def timetrace(message, idstring, tracemessage="TEST_MESSAGE", final=False): """ Trace a message with time stamps. Args: message (str): The actual message coming through idstring (str): An identifier string specifying where this trace is happening. tracemessage (str): T...
98882610b4a184a6918c0be7302bc9117a6f153a
665,082
import re def insert_spaces(text: str) -> str: """Insert space in Chinese characters. >>> insert_spaces("test亨利it四世上") ' test 亨 利 it 四 世 上 ' >>> insert_spaces("test亨利it四世上").strip().__len__() 17 """ return re.sub(r"(?<=[a-zA-Z\d]) (?=[a-zA-Z\d])", "", text.replace("", " "))
27bf13847b717bfaa37fdc79ea21fe7ae3ef9ec4
665,084
def clean_data(record): """Cleans data to get single ',' separated byte messages.""" record = ','.join(record.split()) return record.encode('utf-8')
2098833553bdccbcc6a6f9f7d7ae49b67f2086e5
665,086
from typing import Optional def get_image_provision_timestamp(log_path: str) -> Optional[str]: """ Examines the Travis build log file at `log_path` to determine when the image used by the build was provisioned. :param log_path: The path to the Travis build log. This should be an original build log. :r...
182d351302e4e08a377910bfad409dece9d69456
665,088
def _retain_from_list(x, exclude): """Returns the features to retain. Used in conjunction with H2OTransformer classes that identify features that should be dropped. Parameters ---------- x : iterable of lists The list from which to exclude exclude : array_like The columns ...
a7e8488dcae2a997dc823ff674101a95ada20f78
665,092
import torch def normalized_cross_correlation(x, y, return_map, reduction="mean", eps=1e-8): """ N-dimensional normalized cross correlation (NCC) Args: x (~torch.Tensor): Input tensor. y (~torch.Tensor): Input tensor. return_map (bool): If True, also return the correlation map. ...
f7989de1bcaf449f2a0380198c37a4de92dcbc27
665,094
import pytz def datetime_to_string(dttm): """Given a datetime instance, produce the string representation with microsecond precision""" # 1. Convert to timezone-aware # 2. Convert to UTC # 3. Format in ISO format with microsecond precision if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm)...
d947e06cd75b9e57853fe6cca891911e7d819128
665,095
from typing import Iterable def rgb_hexify(rgb: Iterable[int]) -> str: """Convert a list of RGB numbers to a hex format. """ return ''.join( list(map( lambda x: hex(abs(x))[2:].zfill(2), rgb ))[::-1] )
b3acc17d105de8190a4e386d7e2f71c834601ebe
665,097
def _create_fold_path_component(edge_direction, edge_name): """Return a tuple representing a fold_path component of a FoldScopeLocation.""" return ((edge_direction, edge_name),)
6c169272b4d6052b9d6f9883a17e2f5be0d49193
665,098
def read_header_and_channels(filename, chtrig): """ Reads a txt file with a header and channels and separates them Parameters ---------- filename: str path to the txt Labchart file chtrig : int index of trigger channel Returns ------- header: list header lin...
649d252709cd036264cb9a93abebe5bcf2b1d6b2
665,102
def quads_to_triangles(mesh): """ Convert Quad faces to Triangular ones. Inputs: mesh - an OBJ object loaded from load_obj() Outputs: Modifies the mesh.f and returns mesh. """ newFaces = [] for i, face in enumerate(mesh.f): if(len(face) != 3): assert len(f...
e1deeda6d646b0bb0c192181722967b0b41c9b38
665,103
def stat_lookup(perf_dict, counter_name): """ Performance the lookup of the supplied counter name against the dictionary and returns a counter Id :param perf_dict: The array containing the performance dictionary (with counters and IDs) :param counter_name: The counter name in the correct format for the...
df968b79ccdf87c968edbe0b2ef6f1584a74f49c
665,104
from typing import Union from typing import Optional def _get_event_url( cz_event_id : Union[str,int] ,cz_draw_id : Optional[Union[str,int]] = None )->str: """Returns the cz event page url.""" if cz_draw_id is None: return 'https://curlingzone.com/event.php?view=Scores&eventid=%s#1'%cz_event...
e2492dc76840c4241d5a0202d49eb0eb2be7fe7b
665,106
def to_list(x): """Converts input to a list if necessary.""" if isinstance(x, (list, tuple)): return x else: return [x]
7cfe3e318418318e70a67fa8e871f7993ad59950
665,107
def add_header(response): """Add CORS and Cache-Control headers to the response.""" if not response.cache_control: response.cache_control.max_age = 30 response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET' return response
6e08a6d5958dcd0d46904b218b72b3519cfd283c
665,108
def ascent_set(t): """ Return the ascent set of a standard tableau ``t`` (encoded as a sorted list). The *ascent set* of a standard tableau `t` is defined as the set of all entries `i` of `t` such that the number `i+1` either appears to the right of `i` or appears in a row above `i` or does...
14d1b0872cc461b719827f51532511729597d8f0
665,112
def empty_string_to_none(string): """Given a string, return None if string == "", and the string value (with type str) otherwise """ if string == '': return None else: return str(string)
3510cc65306e56f5845a9f0fbad737e3660d4f2e
665,113
def get_total_tiles(min_zoom: int, max_zoom: int) -> int: """Returns the total number of tiles that will be generated from an image. Args: min_zoom (int): The minimum zoom level te image will be tiled at max_zoom (int): The maximum zoom level te image will be tiled at Returns: The t...
8be77bb05399022385028823b3c1960927b573cc
665,115
def _strip_outliers(w, max_value=1e4, n_devs=5): """Removes work values that are more than 5 (n_devs) standard deviations from the mean or larger than 1E4 (max_value). Parameters ---------- w : list(float) List of works max_value : int, default=1E4 Work values larger than this will ...
6a51005f95587e444c77ab1d4e77d0f9e9a1ea64
665,116
def add_train_args(parser): """Add training-related arguments. Args: * parser: argument parser Returns: * parser: argument parser with training-related arguments inserted """ train_arg = parser.add_argument_group('Train') train_arg.add_argument('--n_batch', ...
578c279a32bbfda96bcbfae9e58631788a2a67da
665,118
from typing import Union from typing import List import json def parse_issues_json_string(issues_json: Union[str, bytes]) -> List[str]: """ Parses a JSON string containing GitHub issues into a list of issue titles. Note: The issue data must contain the `title` field. :param issue_json: Issue data en...
d1db99e0fcc7ec9d9a2a67e4b81f475db57f3c94
665,123
def female_filter(variable): """ Simple function to know the gender by name ending. If name ends with 'a' - it is female's name. """ return variable[-1].lower() == 'a'
0747583f13aeeacc522bf8a7d246625796a45504
665,126
import json def read_config_file(config_filename): """Reads configuration parameters from the specified JSON file.""" # Strip comments while keeping line numbers. config_str = "" with open(config_filename, "r") as f_in: for line in f_in: line = line.rstrip() comment_pos = line.find("//") ...
67a89c89ab44732a6535548181f0d3edd2179a0e
665,129
def cleanString(s): """ takes in a string s and return a string with no punctuation and no upper-case letters""" s = s.lower() for p in "?.!,'": # looping over punctuation s = s.replace(p,'') # replacing punctuation with space return s
4e77343b661f8230cf52681e015246bf67a22163
665,132
def title_case(sentence): """ Converts enetered string into the title_case Parameters ----------- sentence : string string to be converted into sentence case Returns ------- title_case_sentence : string string in TITLE CASE Example ------- >>>title_case('Th...
8cef40ec1f14f78fa4211aaf896b9b2426a0682e
665,133
def makeCd_from_vec(vecCd,nDims,n_neurons): """ convert between vector and matrix forms of C and d""" C = vecCd[:nDims*n_neurons].reshape(nDims,n_neurons).T d = vecCd[nDims*n_neurons:] return C,d
d5360fdcbe88433c7c03b6ede0e0061deff04330
665,135
import hashlib def _validate_file(fpath, md5_hash): """ Validate a file against a MD5 hash. Parameters ---------- fpath: string Path to the file being validated md5_hash: string The MD5 hash being validated against Returns --------- bool True, if the file ...
87677b38205e18c5656e4c660ea1d141e5d3d0b8
665,141
def _clamp_window_size(index, data_size, window_size=200): """Return the window of data which should be used to calculate a moving window percentile or average. Clamped to the 0th and (len-1)th indices of the sequence. E.g. _clamp_window_size(50, 1000, 200) == (0, 150) _clamp_window_size(300...
49f744813f928506c41344c20f6e2b20f54faa17
665,144
from datetime import datetime def utc_timestamp_to_datetime(timestamp): """ Converts timestamp (seconds) to UTC datetime :type timestamp: float | int :rtype: datetime """ return datetime.utcfromtimestamp(round(timestamp))
568c45c0f2c447832707246e9b9fd3d0d1274c2d
665,146
def usafe_filter(entity): """Returns the URL safe key string given an entity.""" return entity.urlsafe
9f5a86e61940e31be51eb09c6e250ebb12401d5f
665,147
import torch from typing import Union def normalise_coords(coords: torch.Tensor, shape: Union[tuple, list]) -> torch.Tensor: """Normalise actual coordinates to [-1, 1] Coordinate locations start "mid-pixel" and end "mid-pixel" (pixel box model): Pixels | 0 | 1 | 2 | | | | ...
fe6820caad41320023b20e52674d3401c4b88fca
665,150
import torch from pathlib import Path from typing import Dict from typing import Any def load_checkpoint(path_to_checkpoint: Path, use_gpu: bool = True) -> Dict[str, Any]: """ Loads a Torch checkpoint from the given file. If use_gpu==False, map all parameters to the GPU, otherwise left the device of all p...
1c76eed4edb742365aabffaa3312d8aeb65d31f2
665,153
import warnings import time def warn_and_continue(exn): """Call in an exception handler to ignore any exception, isssue a warning, and continue.""" warnings.warn(repr(exn)) time.sleep(0.5) return True
a8297d5ceb064bd494f18a0a0a54e83c70229692
665,155
def is_leading_low(x, j): """Return True if bit ``j`` is the lowest bit set in ``x``.""" return x & ((1 << (j+1)) - 1) == 1 << j
cbdfd49dbea663ef0856f62be4b2445bb1ca435d
665,156
import re def colFromRegex(referenceList, regex): """ Return a list created by mapping a regular expression to another list. The regular expression must contain at least one capture group. Parameters ---------- referenceList : list-like A list to derive new values from. regex : str ...
f2f973830dee94a01a133cde345e569ac9ef27bf
665,157
def returns_minus_base(returns, b, masks): """ Subtract optimal baseline from returns :param returns: returns from each step on or for whole trajectory. Size: batch_size x 1 :param b: Optimal baseline per time step for every trajectory. Size: length_time_horizon :param masks: indicate the final step...
5d2432d087adf250ffacb5d4ae6a4ea6628efdf1
665,161
def delta(a, b): """ Kronecker delta function """ return 1 if a == b else 0
2f419de404d984b4ffaddc6e9a5c163722f885d4
665,163
def policy_rollout(env, agent): """Run one episode.""" observation, reward, done = env.reset(), 0, False obs, acts, rews = [], [], [] while not done: env.render() obs.append(observation) action = agent.act(observation) observation, reward, done, _ = env.step(action) ...
9dd1fe588b6f1c78d54e2bc534e411791ba51420
665,165
import ntpath def StripPathToFile( path ): """ Strip a file path down to the last folder/file name. """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
f98f87827b779599c0e84ba88c189cea05961c9d
665,166
from typing import Any def truebool(val: Any | None) -> bool: """Return `True` if the value passed in matches a "True" value, otherwise `False`. "True" values are: 'true', 't', 'yes', 'y', 'on' or '1'. """ return val is not None and str(val).lower() in ("true", "t", "yes", "y", "on", "1")
39fce4719a25175b67f211426374ef98c087175a
665,167
from typing import Dict from typing import Optional def smp_converge(men_engage: Dict[str, Optional[str]], women_engage: Dict[str, Optional[str]]) -> bool: """Return True if there exists a couple that are unengaged.""" return None in men_engage.values() or None in women_engage.values()
731eb1faae978db88ca48766e4796ea321a6a0d3
665,174
def calculate_clipping(cfg, scale): """ Helper function for calculating lo and hi. Args: -- cfg: configuration file for model -- scale: scale for lo, hi. If lo, hi in [0,255], scale is 1. If lo, hi in [0,1], scale is 1/255 Returns: -- LO, HI: list, lower bound and upper bound of each chann...
287f5ec588723e6f4bfe39c40f7fb501df78d161
665,178
def get_attr(f, name): """ Try to access the path `name` in the file `f` Return the corresponding attribute if it is present """ if name in list(f.attrs.keys()): return(True, f.attrs[name]) else: return(False, None)
ad645d2e199fff19697f7bf7d05a4d4769d2c7c9
665,179
from datetime import datetime def format_timestamp(time_string): """Return the timestamp as a formatted string.""" return datetime.strptime(time_string, '%Y%m%d%H%M%S').isoformat().replace('T', ' ')
815952e232777e44c1b711333d1d49e2354688a9
665,180
def get_bbox(img, bbox): """ API expects bbox as [ymin, xmin, ymax, xmax], in relative values, convert to tuple (xmin, ymin, xmax, ymax), in pixel values """ width, height = img.size bbox_px = (0, 0, width, height) if bbox: bbox_px = ( int(bbox[1] * width), int(bb...
96f7c94f8c7b07db510f26fa1dec6695d4c4f275
665,182
import base64 def base64_from_image(image_path): """ Encodes an image in base64 (> str) """ image = open(image_path, 'rb') image_content = image.read() image.close() return(base64.b64encode(image_content).decode('ascii'))
9ffed7f8c746b7dcca0290e9021601f0f8a836c6
665,184
def preprocess_proxy(proxy): """fix proxy list to IPAddress,Port format from dictionary to ipaddress,port Parameters ---------------- proxy : dict proxy details form the proxy json file Returns --------------- dict constaining keys ipaddress and port for the proxy """ ...
482145c8179a79e8323df261213c05bcb408680f
665,190
import pickle import dill def maybe_dill_loads(o): """Unpickle using cPickle or the Dill pickler as a fallback.""" try: return pickle.loads(o) except Exception: # pylint: disable=broad-except return dill.loads(o)
0691a174b5e22cbce5f9830407795a66d9081db3
665,191
from datetime import datetime def format_bybit_candle_timestamp(timestamp: datetime) -> float: """Format Bybit candles timestamp.""" return int(timestamp.timestamp())
b7052e01145200df7951daa24703797d2f64a621
665,195
from typing import Union import math def truncate_to_block(length: Union[int, float], block_size: int) -> int: """ Rounds the given length to the nearest (smaller) multiple of the block size. """ return int(math.floor(length / block_size)) * block_size
cbcd3cfcb2bf32c0cc7d4f00a1b3d5d741113d7d
665,197
def not_caught_by_spamhaus(log_data): """ Returns a dict like log_data but with IPs that were found in zen.spamhaus.org removed. """ return {ip: lists for ip, lists in log_data.items() if "zen.spamhaus.org" not in lists and len(lists) >= 1}
d7e3914dd491f7c4126f17a75fc61bcd51db7c1d
665,200
def construct_path(u,v,discovered): """Use the discovered dictionary from depth-first search to reconstruct a path from node u to node v. """ path = [] # Deal with empty case if v not in discovered: return path # build list of edges # that connect v to u, # then r...
049fd09509765c64ff347f33fffda4719e8d34eb
665,201
import torch def vstack_params(params,new_params): """ Stacks vertically for each key in params, new_params """ assert params.keys() == new_params.keys() res = {k: torch.vstack([params[k], new_params[k]]) for k in params.keys()} return res
2afadfccfd0b54223c531c65aa33ab95e1f37238
665,202
import torch def _cross_squared_distance_matrix(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Pairwise squared distance between two (batch) matrices' rows (2nd dim). Computes the pairwise distances between rows of x and rows of y :param x : 3-D float Tensor :shape: (batc...
1d78e1c34f1333ac4264c4bab0a676305e79c517
665,205
def find_parent_fnames(var): """ Find full names of parents, recursively. These names will be forbidden in the subsequent resolution to make sure there's no back branch in the constructed DAG. """ names = [var.fname] # No self-referential if var.parent: names.append(var.parent.fnam...
e0b32984275a80b14851bba9ecb357a4628d1d54
665,206
import math def sector(angle, radius, rad=False): """Finds the area of a sector of a circle""" if rad: angle = math.degrees(angle) return (angle / 360) * (math.pi * (radius ** 2))
7adcef08a8164eda7f401ddfa2acc7afaae5479e
665,207
from typing import Iterable from functools import reduce def _digits_to_number(digits: Iterable[int]) -> int: """ Gives the number given by its digits, e.g. [1, 2, 3] -> 123 """ return reduce(lambda x, y: x * 10 + y, digits)
10b21394452652658efc5726d73d8e7f7f24c5da
665,209
def form_assignment_string_from_dict(adict): """ Generate a parameter-equals-value string from the given dictionary. The generated string has a leading blank. """ result = "" for aparameter in adict.keys(): result += " {}={}".format(aparameter, adict[aparameter]) return resul...
ea37f0ab0de0e66b4bd3c8745d0d18ed77d1143e
665,210
def tobytes(value): """implicitly try to convert values to byte strings mainly for python 2 and 3 compatibility""" if not isinstance(value, bytes): value = value.encode('utf8') return value
b611d900e5adcbe9bf46e1f2bdcf7ffe6ea5b87c
665,214
def iff( a, b, c ): """ Ternary shortcut """ if a: return b else: return c
f9b01653abd384bd9f942e0fe15fa3b8d396603e
665,217
def searchkit_aggs(aggs): """Format the aggs configuration to be used in React-SearchKit JS. :param aggs: A dictionary with Invenio facets configuration :returns: A list of dicts for React-SearchKit JS. """ return [ {"title": k.capitalize(), "aggName": k, "field": v["terms"]["field"]} ...
7ea577c4503cf8b9b8f9a1b6f396712477040260
665,218
def pre_process_data(full_file_lines): """ I group all the possible configurations in a dictionary the key is MACHINE + BENCHMARK + LOG HEADER :param full_file_lines: :return: dictionary that contains the grouped benchmarks """ grouped_benchmarks = {} for i in full_file_lines: ...
d40e19f4e7e992d7cd1775f516a7fc038e3b059f
665,219