content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import itertools def decaying(start, decay): """Return an iterator of exponentially decaying values. The first value is ``start``. Every further value is obtained by multiplying the last one by a factor of ``decay``. Examples -------- >>> from climin.schedule import decaying >>> s = dec...
ee88365b3a8e768952fc66d02047b60e3e1a34c1
3,613,133
from pytz import timezone from datetime import datetime def chime_local_datetime(*args): """Create a :class:`datetime.datetime` object in Canada/Pacific timezone. Parameters ---------- *args Any valid arguments to the constructor of :class:`datetime.datetime` except *tzinfo*. Local da...
70c0f8bbe53051514ae48e554924e73c5d2f6327
3,613,134
def build_calling_regions(contigs, regions_to_include, regions_to_exclude): """Builds a RangeSet containing the regions we should call variants in. This function intersects the Ranges spanning all of the contigs with those from regions_to_include, if not empty, and removes all of the regions in regions_to_excl...
13d59aedb55c3728559d5434f366448f9df642f7
3,613,135
import inspect def _is_bound_method(the_function: object) -> bool: """ Returns True if fn is a bound method, regardless of whether fn was implemented in Python or in C. """ if inspect.ismethod(the_function): return True if inspect.isbuiltin(the_function): self = getattr(the_fun...
a0d3121c6c4e1c26b2000af73e25a3d772ef2ad3
3,613,136
import urllib import hmac def _is_valid_output_hash(outputs): """Test if a set of outputs have valid hashes on the staging channel. Parameters ---------- outputs : dict A dictionary mapping each output to its md5 hash. The keys should be the full names with the platform directory, ver...
5c750cc9344e12d44c324a0e057d945fe0adcf97
3,613,137
def rm_clusters(name): """ Requires the following pillar to be set: - ceph-salt:execution:fsid """ ret = {'name': name, 'changes': {}, 'comment': '', 'result': False} fsid = __salt__['pillar.get']('ceph-salt:execution:fsid') __salt__['ceph_salt.begin_stage']("Remove cluster {}".format(fsid...
08d4cb05ef1d681891b525196a1fe98e05a5a5ac
3,613,140
def micro_averaged_auprc(df_dict, return_df=False): """ Compute micro-averaged area under the precision-recall curve (AUPRC) from a dictionary of class-wise DataFrames obtained via `evaluate`. """ # List all unique values of thresholds across coarse categories. thresholds = np.unique( np...
b6d53dc94c25d8bf1c66cfa550cacfd90ccca357
3,613,141
def d2vardx2(var, lon, lat, xdim, ydim, cyclic=True, sphere=True): """ calculate second center finite difference along x or longitude. https://bitbucket.org/tmiyachi/pymet/src/8df8e3ff2f899d625939448d7e96755dfa535357/pymet/grid.py :param var: ndarray, grid values. :param lon: array_like, longitude ...
d7ea5abbfca0ff702b42601724d57f414ec52df7
3,613,142
import json def get_chain() -> str: """ Endpoint to query all of the data to display """ chain_data = [] for block in blockchain.chain: chain_data.append(block.__dict__) return json.dumps({"length": len(chain_data), "chain": chain_data})
6a3e0cde6a737e8d706f632556efaafed847de5b
3,613,143
def read_terrace_csv(DataDirectory,fname_prefix): """ This function reads in the csv file with the extension "_terrace_info.csv" and returns it as a pandas dataframe Args: DataDirectory (str): the data directory fname_prefix (str): the name of the DEM Returns: pandas datafr...
7005b47553f8b9d2b6852a58efa751b65d737ba9
3,613,144
import tqdm import torch def eval_net(net, loader, device, n_val): """Evaluation without the densecrf with the dice coefficient""" net.eval() tot = 0 with tqdm(total=n_val, desc='Validation round', unit='img', leave=False) as pbar: for batch in loader: imgs = batch['image'] ...
d3c9d9ce57e51d39c83c894d36817362c8980560
3,613,145
def load_image(file_path, average=True): """ Load data from an image. Parameters ---------- file_path : str Path to a file. average : bool, optional Average a multi-channel image if True. Returns ------- array_like """ if "\\" in file_path: raise Val...
a879f89c9d015181ce43f627f94992796fa0a284
3,613,146
def interp(frame, idx, **args): """ Get interpolated values at indices """ unique_idx = [i for i in idx if i not in frame.index] aug_frame = frame.append(pd.DataFrame(index=unique_idx), sort=True) in_frame = aug_frame.sort_index().interpolate('index', **args) return in_frame.loc[idx, frame.columns]
9a10c48e2998dca2128d46d9fac9f7f70f2d2874
3,613,147
def calcStateTransitionMatrix(orbit, dt, mu=0.0002959122082855911, max_iter=100, tol=1e-15): """ Calculate the state transition matrix for a given change in epoch. The state transition matrix maps deviations from a state at an epoch t0 to a different epoch t1 (dt = t1 - t0). Parameters ---------- ...
3f107a34c0ef11d755065e11766c25e22656322f
3,613,148
def macro_calc(item): """ Calculate PPV_Macro and TPR_Macro. :param item: PPV or TPR :type item:dict :return: PPV_Macro or TPR_Macro as float """ try: item_sum = sum(item.values()) item_len = len(item.values()) return item_sum / item_len except Exception: ...
ec74fe80a4f52d7676beeca1f9abd701043c77af
3,613,149
def convert_from_pj_fat_food(pj_fat_food): """ Convert the given PyJSON Fat-Food to a Natural :param pj_fat_food: The PyJSON Fat-Food being converted :type pj_fat_food: PJ_FatFood :return: The resulting Natural :rtype: Natural """ if not is_pj_fat_food(pj_fat_food): raise ValueError(...
a4e6b635e9406f0bada11f131e09e12e047f299b
3,613,150
def raw_to_multiindex(raw_df, name): """ Takes a raw dataframe (vertically oriented) and transforms it in a multiindexed one. The indices are (date, feature). """ iterables = [raw_df.index, raw_df.columns] index = pd.MultiIndex.from_product(iterables, names=[DATE_COL, FEATURE_COL]) data_df =...
5a02c1a7faf12293a92d4f239cab69351784bf42
3,613,151
def sizeof_fmt(num, suffix='B'): """Size to human readable format. From stack overflow. """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
f4b568f35e152519a12d7a154e93fa71828d5976
3,613,152
from typing import Optional def op_register(tag: str, selector: str, info: str, min_version: Optional[str] = None): """ Decorator used for registering operational-data items with the op catalog. The class being decorated needs to be a subclass of OperationalItem. @param tag: Tag string associated with...
d1271251789a6dfbf3fc29a9dcdeae506f6c02bc
3,613,153
def macdext(candles: np.ndarray, fast_period: int = 12, fast_matype: int = 0, slow_period: int = 26, slow_matype: int = 0, signal_period: int = 9, signal_matype: int = 0, source_type: str = "close", sequential: bool = False) -> MACDEXT: """ MACDEXT - MACD with controllable MA type :...
9cf3db38be7f705a7a3b2c6bf48b4ac601109735
3,613,154
def user_info(): """ 个人中心 :return: """ user = g.user if not user: return credits("/") data = { "user_info":user.to_dict() } return render_template("/news/user.html", data=data)
12b527595323d043ae2a6aef13401ca4c1dd6a20
3,613,155
def height_implied_by_aspect_ratio(W, X, Y): """ Utility function for calculating height (in pixels) which is implied by a width, x-range, and y-range. Simple ratios are used to maintain aspect ratio. Parameters ---------- W: int width in pixel X: tuple(xmin, xmax) x-range i...
8c3225a27f0284acb708434238d4861bb49b0899
3,613,156
def convert_to_valid(seq, correction_dictionary=None, alignment=False): """ Function that converts non-standard amino acid residues to standard ones. Specifically: B -> N U -> C X -> G Z -> Q ' ' -> <empty string> (i.e. an empty space) * -> <empty string> - -> <empty string> (ON...
1fe1f934a6c4ba92be988bb310600aee3356b95c
3,613,157
def CTPixel8_getPixelName(): """CTPixel8_getPixelName() -> char const *""" return _VPLPython.CTPixel8_getPixelName()
01cb3ae9fe00370806f42c15373dca5f856219c1
3,613,158
from datetime import datetime def create_access_token(identity: str) -> bytes: """Create a jwt based on identity.""" payload = { "identity": identity, "exp": datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS), } jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) # ty...
bb257506df76d004466be210bd374a9363b54909
3,613,160
import site def apply_vs30_mod_non_parametric( im_values: pd.DataFrame, site_info: site.SiteInfo, im: IM ) -> pd.Series: """Applies the user vs30 modification for non-parametric data""" assert "PGA" in im_values.columns pga = im_values["PGA"].copy() return im_values[str(im)] * __get_site_amp_rati...
c8006ce81dff810f2505af7f30225b4ad713d175
3,613,161
def calc_earfcn(low_freq_hz: int, high_freq_hz: int) -> int: """ Calculate EARFCN in mhz for CBRS Args: low_freq_hz: int, Low frequency limit taken from available channel high_freq_hz: int, High frequency limit taken from available channel Returns: EARFCN in mhz """ mid...
f757f94d65af96289fd5fe360fceb7a055788c44
3,613,162
def sortino_ratio(returns, required_return=0, period=DAILY): """ Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in tears.create_full_tear_sheet. returns_s...
fffc6552f23f676d9a460e23383300dbc897218a
3,613,163
def confusion_matrix( prediction_detections: ndarray, truth_detections: ndarray, threshold: float = DEFAULT_NEG_THRESHOLD, num_foreground_classes: int = 3, ) -> np.ndarray: """ Compute confusion matrix to evaluate the accuracy of a classification. By definition a confusion matrix :math:`C` is s...
2c12478668e5ea421e98b9dfaaf75638d8c35bb7
3,613,164
def subsol_vector(str1, str2, in11, str3, str4): """subsol_vector(ConstSpiceChar * str1, ConstSpiceChar * str2, ConstSpiceDouble * in11, ConstSpiceChar * str3, ConstSpiceChar * str4)""" return _cspyce0.subsol_vector(str1, str2, in11, str3, str4)
30b59f04243c9b299848408a66eb05eb2f45305f
3,613,165
def compute_per_char(ground_truth, predictions): """ compute per char accuracy :param ground_truth: :param predictions: :return: """ accuracy = [] for index, label in enumerate(ground_truth): prediction = predictions[index] total_count = len(label) correct_count =...
dc33b3cf7890755d9c9ef5901b4201e572323a4a
3,613,166
def getBinaryFormat(name: str) -> type[BinaryFormat]: """ Looks up a binary format by its name attribute. Returns the binary format with the given value for its name attribute. Raises KeyError if there is no match. """ return _formatsByName[name]
41461d9426bac31b934490aacf7b9c1b2d0ba2c4
3,613,167
import scipy import time import numpy import multiprocessing def cholesky_method( A, B=None, gram=False, exponent=1, invert_cholesky=True, cholmod=None): """ Computes trace of inverse of matrix using Cholesky factorization by .. math:: \\mathrm{tra...
a502e29684e0f348b44e6a4897a0904aea503224
3,613,168
def extractNextlevelforthePLOT(item): """ 'Next level for the PLOT' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp is not None or vol is not None or frag is not None) or 'preview' in item['title'].lower(): return None if 'scan-trad' in item['tags']: return None ...
983a0c1a9605922d15ee47be934cdd82bce58517
3,613,169
def kitti_squeezeSeg16_config(): """Specify the parameters to tune below.""" mc = base_model_config('KITTI') mc.CLASSES = ['unknown', 'car', 'pedestrian', 'cyclist'] mc.NUM_CLASS = len(mc.CLASSES) mc.CLS_2_ID = dict(zip(mc.CLASSES, range(len(mc.CLASSES)))) mc...
7ed52b9b20f5f1cc04220df137470fd0050fe2a0
3,613,170
def filter_modules(command_loader, help_file_entries, modules=None, include_whl_extensions=False): """ Modify the command table and help entries to only include certain modules/extensions. : param command_loader: The CLICommandsLoader containing the command table to filter. : help_file_entries: The dict of...
2f0ec2164a67abc9c691e66a0470977a06d51b97
3,613,171
from texar.agents.agent_utils import Space def convert_gym_space(spc): """Converts a :gym:`gym.Space <#spaces>` instance to a :class:`~texar.agents.Space` instance. Args: spc: An instance of `gym.Space` or :class:`~texar.agents.Space`. """ if isinstance(spc, Space): re...
d9362e00a95a76a60d9aaf6b6935dc9ec5bb92d6
3,613,173
from typing import List def save_inventory( session: SessionABC, inventory: List[InventoryType], merge_samples: bool = False ) -> List[InventoryType]: """Saves a list of inventory items to the server. :param session: the AqSession instance :param inventory: list of inventory items :param merge_sa...
d01956ba2334a3ab824845a4db3261fbdec25a94
3,613,174
def positional_encoding(max_position, d_model): """Return the tensor encoding the position of elements in a sequence Compute the positional encoding with a combination of sinusoidal functions as suggested in (Vaswani at al., "Attention is all you need", 2017) Note: When we add the positional e...
7ecc8ba093ab9be744ba945975fdb57570fc09be
3,613,175
import re def get_namespace(element): """Extract the namespace using a regular expression.""" match = re.match(r"\{.*\}", element.tag) return match.group(0) if match else ""
9380e104d05ae6b56463b96bf87d9c0fcd8202cf
3,613,176
import numpy def create_LOFAR_configuration(antfile: str, meta: dict = None, params={}): """ Define from the LOFAR configuration file :param antfile: :type str: :param name: :type str: :param meta: :type dict: :param params: Dictionary containing paramet...
affed3d6e7c7fa24d434fb51af5f15648a7e202e
3,613,178
import random def get_fittest_solution(solutions): """Return the fittest of the passed solutions, using tie-breaking criteria if there are ties and only using random tie-breaking as a last resort""" # ensure that there are solutions if not solutions: return None # a single solution is the ...
9bdf8274e9f8be491da2de14b76114e95c4f0584
3,613,179
import itertools def sphere_plane(map, mapi) -> plt.Figure: """ Plots map from (3d) sphere to (2d) plane and its inverse. :param map: Map from sphere to plane. :param mapi: Map from plane to sphere. :return: Figure. """ # Init plot object: fig = plt.figure() ax = np.array([[fig.ad...
a07d747fd0e1a12629591a3fdd8db2a71b6ba8e2
3,613,181
import json import hashlib def hash_config(configuration: dict) -> str: """Computes a SHA256 hash from a dictionnary. Args: configuration (dict): The configuration to hash Returns: str: _description_ """ stringified = json.dumps(configuration, sort_keys=True) return hashlib.s...
ccf30915fc736ce4724eb0ceceab59220e94efd0
3,613,182
def get_bag_of_communities(network, partition): """ :param network: dictionary containing for each key (each node/page) a dictionary containing the page categories. :param partition: list of the community assignment :return: list of dictionaries, one dictionary per community. Each dictionary contains th...
615e88393b30b1989d98eeea1ac7123588a51ea9
3,613,183
import asyncio def connect( stream_generator, user=None, database=None, password=None, loop=None, **kwargs): """Creates a connection to a PostgreSQL database. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_; however, the arguments of the function are...
954e5a0b3bdb2718910f6f50df7064966fdc806f
3,613,184
def add_neighbor_count_features(edge_df, X_df, structures_df): """ edge_df must be symmetric. """ cnt_df = edge_df.groupby( ['molecule_name', 'atom_index_0']).size().to_frame('EF_neighbor_count') cnt_df.reset_index(inplace=True) cnt_df.rename({'atom_index_0': 'atom_index_zero'}, inplace=...
688e04893035f1340c7a14a0173f7059604665cb
3,613,185
def _to_pascal_case(value: str) -> str: """Converts a snake_case string into a PascalCase one.""" value = value.replace("-", "_") if value.find("_") == -1: return value[0].upper() + value[1:] return "".join([v.capitalize() for v in value.split("_")])
d41985f1d182b723c9861473e4f9eca8c7a7977e
3,613,186
import yaml def load(modelSpecFilename): """ Need the following items in the model spec file: costFn decisionFn stages specs :param modelSpecFilename: :return: """ with open(modelSpecFilename) as f: modelDict = yaml.load(f) for stageDict in modelDict['specs']: ...
5033aec67b5f0a19651cdffe96b5ce5e704aa816
3,613,187
from typing import Any from typing import Union from typing import Set import re def _replace_prefixed(text: Any, prefix: Union[str, Set[str]], value: str) -> Any: """ Replace all substrings starting with the prefix(es) with the value. """ if pd.isna(text): return text text = str(text) ...
cc034958d2e175e93ef9fdb252e7e0e66e2442f2
3,613,188
def perma(mat,m): """ Permanent of the matrix """ if not mat.isSquare: return None if mat.isIdentity: return 1 if mat.dim[0]==2: return m[0][0]*m[1][1] + m[1][0]*m[0][1] if mat.dim[0]==3: return (m[0][0]*m[1][1]*m[2][2] + m[0][1...
71e2408c79e09b4fa5eb328130d2b5b7e7efdf41
3,613,189
def realtime_to_gametime(secs=0, mins=0, hrs=0, days=1, weeks=1, months=1, yrs=0, format=False): """ This method calculates how much in-game time a real-world time interval would correspond to. This is usually a lot less interesting than the other way around. Keyword Args: times (int): The ...
3fa4c85f4f5a71357c64d4aab53248b348736a10
3,613,190
def char_class_abbrev(cc_abbrev: str, **config): """ Constructs a char_class spec :param cc_abbrev: alternative type abbreviation i.e. ascii, cc-ascii, visible, cc-visible :param config: in **kwargs format :return: the char_class spec """ spec = { "type": 'char_class_abbrev' } ...
da14e16657cf5666bde881c0a27d995327878ecb
3,613,191
def trial_division(n): """Return a list of the prime factors for a natural number.""" if n < 2: return [] prime_factors_list = [] temp = primeGenerate(int(n**0.5) + 1) for p in temp: if p*p > n: break while n % p == 0: prime_factors_list.append(p) ...
1c5dc9beb3ca237e2a7f663cb7e864bfb42c3141
3,613,193
def occlusion(net: Module, input_image: Tensor, n_top_classes: int = 3) -> Tensor: """Creates a attribution heatmap by occluding parts of the input image. Args: net: the network to visualize attribution for input_image: image tensor of dimensions (c, h, w) or (1, c, h, w) n_top_classes:...
e40c1ecf7293fe5b0d51de999b5f4cad3d3d2dd1
3,613,194
def log_pos(x): """Computes log with the assumption that x values are positive. """ return jnp.log(jnp.maximum(x, jnp.finfo(float).eps))
f963ed2a38b9d81ed05e698da66a0c4e3c96a47e
3,613,195
from typing import List import json def import_tree_to_json_str(imports=List[Import]) -> str: """ Print the imported modules tree in json format. """ exclude_root = imports[0]["nested_imports"] return json.dumps(exclude_root, indent=2)
8796c1099fb39d8cac72a50e83da23ca25e1f821
3,613,197
from typing import Tuple def place_targets_with_goal_distance_ratio( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, object_placements: np.ndarray, goal_distance_ratio: float, goal_distance_min: float, max_placement_...
26962960db0d6a4c4681890d553cafe0d78150f7
3,613,198
import torch import tqdm def predict(model, test_batch_generator, num_batches, device, label_map, class_weight): """ Main evaluation routine """ epoch_loss = 0 epoch_acc = 0 epoch_results = {} epoch_results_by_tag = {} epoch_CR = "" output_t_pred = None model.eval() with ...
0ec7d472a4cc2b17ecd5e6a033243300e1184f60
3,613,199
def using_cumisc(handle=None): """Temporarily set chainer's CUBLAS handle to scikit-cuda. The usage is similar to :func:`using_device`. Args: handle: CUBLAS handle. If ``None`` is specified, it uses CUBLAS handle for the current device. Returns: CumiscUser: Misc user objec...
8cb4bd00f63e8a856ea315eec9452b17f6ece08d
3,613,201
def remove_list_duplicates(my_list: list) -> list: """ Removes any duplicated values from a list. """ return list(dict.fromkeys(my_list))
e3dd86733117fce7bad2860d860b98b349efcfb5
3,613,202
from typing import Union from typing import Iterable def sql_from_binary_tree(X: Union[list, np.ndarray], children_left: Union[list, np.ndarray], children_right: Union[list, np.ndarray], feature: Union[list, np.ndarray], ...
177b6172846a8187fd398b2d098c46f522633eec
3,613,203
from typing import Callable import click def target_id_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for choosing a target ID. """ click_option_function: Callable[ [Callable[..., None]], Callable[..., None], ] = click.option( '--target...
1fe67f22e00b4d4930af347c482d28e30032508d
3,613,204
def tdnsresp(**kwargs) -> dns.Message: """ Returns: mitmproxy.dns.Message """ default = dict( timestamp=946681201, id=42, query=False, op_code=dns.op_codes.QUERY, authoritative_answer=False, truncation=False, recursion_desired=True, ...
ae4f0080b37fc7fd9f2efa6ec1daf85e990c130b
3,613,205
def __fetch_query_from_uuid(uuid: str) -> bigquery.BigQueryResult: """ Fetches a cached BigQuery result from its UUID. Args: uuid (str): The UUID of the query to be retrieved. Returns: (BigQueryResult): The corresponding BigQuery result object. """ # Fetch cached qu...
c7f0c5bb1ac94dea6c251a8ecf0c52cdad1fd6c7
3,613,207
def _get_keys(response): """ return lists of strings that are the keys from a client.list_objects() response """ keys = [] if 'Contents' in response: objects_list = response['Contents'] keys = [obj['Key'] for obj in objects_list] return keys
dfa1f066ac19138920509935b1dbbdde52591f18
3,613,208
def round_updown_to_x(num_in, x, direction="up"): """ Rounds a given value (num_in) to the nearest multiple of x, in a given direction (up or down) :param num_in: Input value :param x: Value to round to a multiple of :param direction: Round up or down. Default: 'up' :return: Rounded number ...
206b582843eea234b5b655dddd54eea6e32eec42
3,613,209
async def player_stop(): """ Full route: /music/player/resume Request (JSON): None Stop (unload) the current song. """ # no json expected was_playing = await player.player_stop() if was_playing: return with_status(None, 200, StatusType.OK) else: return with_status...
320c71a1ca669b6a2b386f8b3ab500b78a1b70b4
3,613,210
async def revocation_registries_created(request: web.BaseRequest): """ Request handler to get revocation registries that current agent created. Args: request: aiohttp request object Returns: List of identifiers of matching revocation registries. """ context = request.app["requ...
0adc59382ffc991fb7d5c7e191aa960b0db2d516
3,613,211
def vwap(bars): """ calculate vwap of entire time series (input can be pandas series or numpy array) bars are usually mid [ (h+l)/2 ] or typical [ (h+l+c)/3 ] """ typical = ((bars['high'] + bars['low'] + bars['close']) / 3).values volume = bars['volume'].values return pd.Series(index=ba...
06d6554b301c229f8679f5a987f651ac09956b4e
3,613,212
import jqmobile from xml.dom import minidom import re def get_svn_revision(path=None): """ Returns the SVN revision in the form SVN-XXXX, where XXXX is the revision number. Returns SVN-unknown if anything goes wrong, such as an unexpected format of internal SVN files. If path is provided, it...
20db6d1b3e4d9190d736ac43b93626eacb652a6d
3,613,213
def checkFrameRateChange_Lenient(op, graph, frm, to): """ Confirm frame rate has not changed. :param op: :param graph: :param frm: :param to: :return: """ if _checkFrameRateChange(op, graph, frm, to): return (Severity.WARNING, 'Frame Rate Changed between nodes')
f8e5a32906e2b1d231b20796ea8fb3481b6ee6d1
3,613,214
def img2port(img_url): """ mimvp.com的端口号用图片来显示, 本函数将图片url转为端口, 目前的临时性方法并不准确 """ code = img_url.split("=")[-1] if code.find("AO0OO0O")>0: return 80 else: return None
60768ee0723808ef7d1f3e74287b7a6e576f94c5
3,613,215
def coverage(tiles): """Sum of length of all tiles. """ accu = 0 for tile in tiles: accu = accu + tile[2] return accu
b2cbb6b926e070d9fc457523bb60169ef9b70821
3,613,216
import pytz from datetime import datetime async def stations(id: int, date_from: str = None, date_to: str = None, param: str = 'pm25'): """ Get pollution data for a specific station and a date range :return: json of format {"data": [{date, time, value}, ...] """ if not date_from or not date_to: ...
4971e81dc696c32f072f38b2da40f7a2a710bc7e
3,613,217
def update(head: str, td: Tag) -> Attr: """ Update a developing part dictionary based on a cell from the product table :param head: The head string from the <th> :param td: The <td> from the product table :return The applicable CSS class, and the dictionary with kvs to update. """ cl...
7f3ba66b1158f08f9e2f7f13afd7908a1c0ba6a9
3,613,218
import errno def load_doc(name, doctype = None, project = None): """Load document Args: name: Name of document (file must exist in :/username/project/docs.zip: file). doctype: Type of document. 'pdf', 'docx', etc. project: reference to ArthurProject object. Returns: list:...
31245e378be54c8933dfe1e38644c32f22bce110
3,613,219
def lognormalize_chroma(C): """Log-normalizes chroma such that each vector is between -80 to 0.""" C += np.abs(C.min()) + 0.1 C = C / C.max(axis=0) C = 80 * np.log10(C) # Normalize from -80 to 0 return C
977f8fac9b16bfd32c331d6ee713864a61f930d0
3,613,220
def kei_zeros(nt): """Compute nt zeros of the Kelvin function kei x """ if not isscalar(nt) or (floor(nt) != nt) or (nt <= 0): raise ValueError("nt must be positive integer scalar.") return specfun.klvnzo(nt,4)
0a92514543ee9ff0bacdd18a1eb9136be366f6f6
3,613,221
def _reflect_particle_diffusive(arr, **kwargs): """ Reflect particles given in a diffusive manner. Args: arr (np.ndarray): 2D-ndarray of shape *number of particles x 5*. Each particle is describes by : [x, y, vx, vy, vz] Returns: [np.ndarray]: returns the modified array by default (in most...
0b2fd08c2c6b367275ad139b0915432653fb164c
3,613,222
def get_int() -> int: """ Gets a lone integer from the console (the integer is on its own line) :return: The int value that was read in from the console """ line = input().strip() return int(line)
1bffcb1c5c1e7910a11358d4616a747b38ba3d73
3,613,224
import tqdm def plot_tract_profiles( X, groups, group_names, group_by=None, group_by_name=None, bins=None, quantiles=None, palette="colorblind", ci=95.0, subplot_positions=None, nrows=None, ncols=None, ): """Plot profiles for each bundle and each metric. Parame...
9a174dadabc0463b7072ad451b8a03d8c0610ed9
3,613,225
def regex_search_matches_output(get_output, search): """ Applies a regex search func to the current output """ return search(get_output())
6f054990d3454a447656567b3ceb12a38c2809a5
3,613,226
def crop(img, start_y, start_x, h, w): """ Crop an image given the top left corner. :param img: The image :param start_y: The top left corner y coord :param start_x: The top left corner x coord :param h: The result height :param w: The result width :return: The cropped image. """ ...
cb3a05989f1538bcec34102c33291d500a21c59d
3,613,227
def validate_existing_delivery(start, end, queryset): """Validate if exists a deliver at that time by date""" delivery_exist = False msg = "" if len(queryset): for deliver in queryset: deliver_start = format_date(deliver.start) deliver_end = format_date(deliver.end) ...
5f8a612ed84e47f73fd084d2319e3f0c2b446204
3,613,230
def separate_by_class(train): """ For each dependent variable (last column of DF) value, map to corresponding rows of the DF """ classifications = set(train[:, -1]) return {c: train[train[:, -1] == c] for c in classifications}
1ed0fd5c077a0d7391955687ec190ded873a9bee
3,613,231
def plot_profile(datasets, fields=None, times=None, timerange=None, fig=None,ax=None, fieldlimits=None, heightlimits=None, fieldlabels={}, cmap=None, stack_by_datasets...
996d267a8bd21e24d26aad56e38e6d67fdec3997
3,613,232
def abs(v): """Create abs in the sense of distance instead of just vanishing the sign. Create abs in the sense of distance instead of vanishing the sign. Used to calculate the length of coordinates, or anything that can be interpreted as coordinate. Args ---- v: iterable of float, comp...
effdbb763a1b9e1f04137139eef3f94e662e3cc7
3,613,233
from pathlib import Path def confirm_index_opts(taxonomy_name, opts): """Confirm expected keys are present in opts for indexing.""" file_key = "taxonomy-%s-file" % taxonomy_name url_key = "taxonomy-%s-url" % taxonomy_name for key in {"taxonomy-path", file_key}: if key not in opts: ...
904412613fabe115d368d3dfa77ac9be3f355f15
3,613,234
import json def podcast_spider(site): """ 更新源内容 """ resp = get_with_retry(site.rss) if resp is None: logger.info(f"RSS 源可能失效了`{site.rss}") return None feed_obj = feedparser.parse(BytesIO(resp.content)) for entry in feed_obj.entries: # 有些是空的 if not entry: ...
6151350572181b0776b075af1daa80ac0559fcbf
3,613,235
import xml.etree.cElementTree as ET def getDataSetUuid(xmlfile): """ Quickly retrieve the uuid from the root element of a dataset XML file, using a streaming parser to avoid loading the entire dataset into memory. Returns None if the parsing fails. """ try: for event, element in ET.ite...
7386efea461056f8f4b472923b8f4a30d6d80d3b
3,613,236
def train_mnist_single_machine(data_dir, num_epochs, use_fake_data=False): """Train a ConvNet on MNIST. Args: data_dir: string. Directory to read MNIST examples from. num_epochs: int. Number of passes to make over the training set. use_fake_data: bool. If True, generate a synthetic dataset. Returns:...
ab4485e898d54122730b9cc82f9d8a7cd2c04140
3,613,237
def pick_word(probabilities, int_to_vocab): """ Pick the next word with some randomness :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word """ return np.random.choice(list(int_to_vocab.values())...
84c9c46133d799313a490c7cc7a03b2dcb776415
3,613,238
def get_max_cost_matrix(a, bottom_right=True, top_left=False): """Return matrix with maximum cost for paths from all nodes""" maxcost = 9 * a.shape[0] * a.shape[1] cost = np.zeros(a.shape, int) + maxcost if bottom_right: cost[-1, -1] = 0 if top_left: cost[0, 0] = 0 return cost
156ef55507558d7b194d51f8dd6533bb6b34925e
3,613,239
def get_synthetic_data(data_size: int, features_num: int) -> (Matrix, ColumnVector): """ A method which creates a random matrix of ``size data_size x features_num`` and a ``random 1 x data_size`` random vector. Args: data_size(int): The number of samples in the data - ``n``. features_nu...
bddea3bff042d219f8b9992fa17aecadcbe41e0a
3,613,240
from typing import Union def injection_volume(val: Union[float, str]) -> Union[int, str]: """ Handle special case for injection volume of ``-1``, which indicates "As Method". :param val: :type val: :return: :rtype: """ if val in {-1, "-1"}: return "As Method" else: return int(val)
b09240b9c8bd0eebfb7880494f75b105e313b228
3,613,241
from typing import Optional def validate_charge_efficiency(charge_efficiency: Optional[float]) -> Optional[float]: """ Validates the charge efficiency of an object. Charge efficiency is always optional. :param charge_efficiency: The charge efficiency of the object. :return: The validated charge e...
46e40fcdc65ffec453f1bac9bd03f6a9297647fd
3,613,242
def get_module_info(*args): """ get_module_info(ea, modinfo) -> bool """ return _ida_dbg.get_module_info(*args)
3d93e2552418968fb9ad2f7343e7f826f00fbe7a
3,613,243
def set_graph_attributes(species): """ For a molecular species set the π bonds and stereocentres in the molecular graph. Arguments: species (autode.species.Species): """ logger.info('Setting the π bonds in a species') def is_idx_pi_atom(idx): return is_pi_atom(atom_label=sp...
1513a26fb657b6b318511156271eb7ad86eda8e5
3,613,245
def yices_check_context_with_model(ctx, params, mdl, n, t): """Check satisfiability modulo a model. Check whether the assertions stored in ctx conjoined with a model are satisfiable. - ctx must be a context initialized with support for MCSAT (see yices_new_context, yices_new_config, yices_set_c...
50b7204122de1d1eb295a1d04b9a3b1dd5e2b738
3,613,246